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#include "libbb.h"
40
41int uniq_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
42int uniq_main(int argc UNUSED_PARAM, char **argv)
43{
44 const char *input_filename;
45 unsigned skip_fields, skip_chars, max_chars;
46 unsigned opt;
47 char *cur_line;
48 const char *cur_compare;
49
50 enum {
51 OPT_c = 0x1,
52 OPT_d = 0x2,
53 OPT_u = 0x4,
54 OPT_f = 0x8,
55 OPT_s = 0x10,
56 OPT_w = 0x20,
57 };
58
59 skip_fields = skip_chars = 0;
60 max_chars = INT_MAX;
61
62 opt = getopt32(argv, "cduf:+s:+w:+", &skip_fields, &skip_chars, &max_chars);
63 argv += optind;
64
65 input_filename = argv[0];
66 if (input_filename) {
67 const char *output;
68
69 if (input_filename[0] != '-' || input_filename[1]) {
70 close(STDIN_FILENO);
71 xopen(input_filename, O_RDONLY);
72 }
73 output = argv[1];
74 if (output) {
75 if (argv[2])
76 bb_show_usage();
77 if (output[0] != '-' || output[1]) {
78
79
80
81 xmove_fd(xopen(output, O_WRONLY | O_CREAT | O_TRUNC), STDOUT_FILENO);
82 }
83 }
84 }
85
86 cur_compare = cur_line = NULL;
87
88 do {
89 unsigned i;
90 unsigned long dups;
91 char *old_line;
92 const char *old_compare;
93
94 old_line = cur_line;
95 old_compare = cur_compare;
96 dups = 0;
97
98
99 while ((cur_line = xmalloc_fgetline(stdin)) != NULL) {
100 cur_compare = cur_line;
101 for (i = skip_fields; i; i--) {
102 cur_compare = skip_whitespace(cur_compare);
103 cur_compare = skip_non_whitespace(cur_compare);
104 }
105 for (i = skip_chars; *cur_compare && i; i--) {
106 ++cur_compare;
107 }
108
109 if (!old_line || strncmp(old_compare, cur_compare, max_chars)) {
110 break;
111 }
112
113 free(cur_line);
114 ++dups;
115 }
116
117 if (old_line) {
118 if (!(opt & (OPT_d << !!dups))) {
119 if (opt & OPT_c) {
120
121 printf("%7lu ", dups + 1);
122 }
123 puts(old_line);
124 }
125 free(old_line);
126 }
127 } while (cur_line);
128
129 die_if_ferror(stdin, input_filename);
130
131 fflush_stdout_and_exit(EXIT_SUCCESS);
132}
133