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 FILE *xgetoptfile_uniq_s(char **argv, int read0write2)
21 if ((*n != '-') || n[1]) {
22 return xfopen(n, "r\0w" + read0write2);
25 return (read0write2) ? stdout : stdin;
28 int uniq_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
29 int uniq_main(int argc UNUSED_PARAM, char **argv)
32 const char *s0, *e0, *s1, *e1, *input_filename;
34 unsigned skip_fields, skip_chars, max_chars;
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 in = xgetoptfile_uniq_s(argv, 0);
60 out = xgetoptfile_uniq_s(argv, 2);
61 if (*argv && argv[1]) {
65 s1 = e1 = NULL; /* prime the pump */
72 /* gnu uniq ignores newlines */
73 while ((s1 = xmalloc_fgetline(in)) != NULL) {
75 for (i = skip_fields; i; i--) {
76 e1 = skip_whitespace(e1);
77 e1 = skip_non_whitespace(e1);
79 for (i = skip_chars; *e1 && i; i--) {
83 if (!s0 || strncmp(e0, e1, max_chars)) {
87 ++dups; /* note: testing for overflow seems excessive. */
91 if (!(opt & (OPT_d << !!dups))) { /* (if dups, opt & OPT_e) */
92 fprintf(out, "\0%ld " + (opt & 1), dups + 1); /* 1 == OPT_c */
93 fprintf(out, "%s\n", s0);
99 die_if_ferror(in, input_filename);
101 fflush_stdout_and_exit(EXIT_SUCCESS);