1 /* vi: set sw=4 ts=4: */
3 * uniq implementation for busybox
5 * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /* BB_AUDIT SUSv3 compliant */
24 /* http://www.opengroup.org/onlinepubs/007904975/utilities/uniq.html */
32 #include "libcoreutils/coreutils.h"
34 static const char uniq_opts[] = "f:s:cdu\0\7\3\5\1\2\4";
36 int uniq_main(int argc, char **argv)
39 /* Note: Ignore the warning about dups and e0 being used uninitialized.
40 * They will be initialized on the fist pass of the loop (since s0 is NULL). */
41 #warning The dups and e0 warnings are OK, ignore them
42 unsigned long dups, skip_fields, skip_chars, i;
43 const char *s0, *e0, *s1, *e1, *input_filename;
45 int uniq_flags = 6; /* -u */
47 skip_fields = skip_chars = 0;
49 while ((opt = getopt(argc, argv, uniq_opts)) > 0) {
51 skip_fields = bb_xgetularg10(optarg);
52 } else if (opt == 's') {
53 skip_chars = bb_xgetularg10(optarg);
54 } else if ((s0 = strchr(uniq_opts, opt)) != NULL) {
62 input_filename = *(argv += optind);
64 in = xgetoptfile_sort_uniq(argv, "r");
68 out = xgetoptfile_sort_uniq(argv, "w");
69 if (*argv && argv[1]) {
75 /* gnu uniq ignores newlines */
76 while ((s1 = bb_get_chomped_line_from_file(in)) != NULL) {
78 for (i=skip_fields ; i ; i--) {
79 e1 = bb_skip_whitespace(e1);
80 while (*e1 && !isspace(*e1)) {
84 for (i = skip_chars ; *e1 && i ; i--) {
88 if (strcmp(e0, e1) == 0) {
89 ++dups; /* Note: Testing for overflow seems excessive. */
93 if ((dups && (uniq_flags & 2)) || (!dups && (uniq_flags & 4))) {
94 bb_fprintf(out, "\0%7d\t" + (uniq_flags & 1), dups + 1);
95 bb_fprintf(out, "%s\n", s0);
110 bb_xferror(in, input_filename);
112 bb_fflush_stdout_and_exit(EXIT_SUCCESS);