1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41#include "libbb.h"
42
43int uniq_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
44int uniq_main(int argc UNUSED_PARAM, char **argv)
45{
46 const char *input_filename;
47 unsigned skip_fields, skip_chars, max_chars;
48 unsigned opt;
49 char eol;
50 char *cur_line;
51 const char *cur_compare;
52
53 enum {
54 OPT_c = 1 << 0,
55 OPT_d = 1 << 1,
56 OPT_u = 1 << 2,
57 OPT_f = 1 << 3,
58 OPT_s = 1 << 4,
59 OPT_w = 1 << 5,
60 OPT_i = 1 << 6,
61 OPT_z = 1 << 7,
62 };
63
64 skip_fields = skip_chars = 0;
65 max_chars = INT_MAX;
66
67 opt = getopt32(argv, "cduf:+s:+w:+iz", &skip_fields, &skip_chars, &max_chars);
68 argv += optind;
69
70 input_filename = argv[0];
71 if (input_filename) {
72 const char *output;
73
74 if (input_filename[0] != '-' || input_filename[1]) {
75 close(STDIN_FILENO);
76 xopen(input_filename, O_RDONLY);
77 }
78 output = argv[1];
79 if (output) {
80 if (argv[2])
81 bb_show_usage();
82 if (output[0] != '-' || output[1]) {
83
84
85
86 xmove_fd(xopen(output, O_WRONLY | O_CREAT | O_TRUNC), STDOUT_FILENO);
87 }
88 }
89 }
90
91 cur_compare = cur_line = NULL;
92 eol = (opt & OPT_z) ? 0 : '\n';
93
94 do {
95 unsigned i;
96 unsigned long dups;
97 char *old_line;
98 const char *old_compare;
99
100 old_line = cur_line;
101 old_compare = cur_compare;
102 dups = 0;
103
104
105 while ((cur_line = xmalloc_fgetline(stdin)) != NULL) {
106 cur_compare = cur_line;
107 for (i = skip_fields; i; i--) {
108 cur_compare = skip_whitespace(cur_compare);
109 cur_compare = skip_non_whitespace(cur_compare);
110 }
111 for (i = skip_chars; *cur_compare && i; i--) {
112 ++cur_compare;
113 }
114
115 if (!old_line)
116 break;
117 if ((opt & OPT_i)
118 ? strncasecmp(old_compare, cur_compare, max_chars)
119 : strncmp(old_compare, cur_compare, max_chars)
120 ) {
121 break;
122 }
123
124 free(cur_line);
125 ++dups;
126 }
127
128 if (old_line) {
129 if (!(opt & (OPT_d << !!dups))) {
130 if (opt & OPT_c) {
131
132 printf("%7lu ", dups + 1);
133 }
134 printf("%s%c", old_line, eol);
135 }
136 free(old_line);
137 }
138 } while (cur_line);
139
140 die_if_ferror(stdin, input_filename);
141
142 fflush_stdout_and_exit(EXIT_SUCCESS);
143}
144