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