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 unsigned long dups, skip_fields, skip_chars, i;
40 const char *oldline, *oldskipped, *line, *skipped, *input_filename;
42 int uniq_flags = 6; /* -u */
44 skip_fields = skip_chars = 0;
46 while ((opt = getopt(argc, argv, uniq_opts)) > 0) {
47 if (opt == 'f') skip_fields = bb_xgetularg10(optarg);
48 else if (opt == 's') skip_chars = bb_xgetularg10(optarg);
49 else if ((line = strchr(uniq_opts, opt)) != NULL) {
50 uniq_flags &= line[4];
51 uniq_flags |= line[7];
52 } else bb_show_usage();
55 input_filename = *(argv += optind);
57 in = xgetoptfile_sort_uniq(argv, "r");
59 out = xgetoptfile_sort_uniq(argv, "w");
60 if (*argv && argv[1]) bb_show_usage();
64 /* gnu uniq ignores newlines */
65 while ((line = bb_get_chomped_line_from_file(in)) != NULL) {
67 for (i=skip_fields ; i ; i--) {
68 skipped = bb_skip_whitespace(skipped);
69 while (*skipped && !isspace(*skipped)) ++skipped;
71 for (i = skip_chars ; *skipped && i ; i--) ++skipped;
73 if (strcmp(oldskipped, skipped) == 0) {
74 ++dups; /* Note: Testing for overflow seems excessive. */
78 if ((dups && (uniq_flags & 2)) || (!dups && (uniq_flags & 4))) {
79 bb_fprintf(out, "\0%7d\t" + (uniq_flags & 1), dups + 1);
80 bb_fprintf(out, "%s\n", oldline);
82 free((void *)oldline);
95 bb_xferror(in, input_filename);
97 bb_fflush_stdout_and_exit(EXIT_SUCCESS);