1 /* vi: set sw=4 ts=4: */
3 * uniq implementation for busybox
5 * Copyright (C) 2005 Manuel Novoa III <mjn3@codepoet.org>
7 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
10 /* BB_AUDIT SUSv3 compliant */
11 /* http://www.opengroup.org/onlinepubs/007904975/utilities/uniq.html */
15 static void xgetoptfile_uniq_s(const char *n, int fd)
19 if ((n[0] == '-') && !n[1])
21 /* close(fd); - optimization */
24 (fd == STDIN_FILENO) ? O_RDONLY : (O_WRONLY | O_CREAT | O_TRUNC),
29 int uniq_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
30 int uniq_main(int argc UNUSED_PARAM, char **argv)
32 const char *input_filename;
33 unsigned skip_fields, skip_chars, max_chars;
36 const char *cur_compare;
40 OPT_d = 0x2, /* print only dups */
41 OPT_u = 0x4, /* print only uniq */
47 skip_fields = skip_chars = 0;
50 opt_complementary = "f+:s+:w+";
51 opt = getopt32(argv, "cduf:s:w:", &skip_fields, &skip_chars, &max_chars);
54 input_filename = *argv;
56 xgetoptfile_uniq_s(*argv, STDIN_FILENO);
60 xgetoptfile_uniq_s(*argv, STDOUT_FILENO);
61 if (*argv && argv[1]) {
65 cur_compare = cur_line = NULL; /* prime the pump */
71 const char *old_compare;
74 old_compare = cur_compare;
77 /* gnu uniq ignores newlines */
78 while ((cur_line = xmalloc_fgetline(stdin)) != NULL) {
79 cur_compare = cur_line;
80 for (i = skip_fields; i; i--) {
81 cur_compare = skip_whitespace(cur_compare);
82 cur_compare = skip_non_whitespace(cur_compare);
84 for (i = skip_chars; *cur_compare && i; i--) {
88 if (!old_line || strncmp(old_compare, cur_compare, max_chars)) {
93 ++dups; /* testing for overflow seems excessive */
97 if (!(opt & (OPT_d << !!dups))) { /* (if dups, opt & OPT_u) */
98 printf("\0%lu " + (opt & 1), dups + 1); /* 1 == OPT_c */
99 printf("%s\n", old_line);
105 die_if_ferror(stdin, input_filename);
107 fflush_stdout_and_exit(EXIT_SUCCESS);