3 * comm.c - select or reject lines common to two files
5 * Copyright 2012 Ilya Kuzmich <ikv@safe-mail.net>
7 * See http://opengroup.org/onlinepubs/9699919799/utilities/comm.html
9 // <# and ># take single digit, so 321 define flags
10 USE_COMM(NEWTOY(comm, "<2>2321", TOYFLAG_USR|TOYFLAG_BIN))
16 usage: comm [-123] FILE1 FILE2
18 Reads FILE1 and FILE2, which should be ordered, and produces three text
19 columns as output: lines only in FILE1; lines only in FILE2; and lines
20 in both files. Filename "-" is a synonym for stdin.
22 -1 suppress the output column of lines unique to FILE1
23 -2 suppress the output column of lines unique to FILE2
24 -3 suppress the output column of lines duplicated in FILE1 and FILE2
30 static void writeline(const char *line, int col)
32 if (col == 0 && toys.optflags & FLAG_1) return;
34 if (toys.optflags & FLAG_2) return;
35 if (!(toys.optflags & FLAG_1)) putchar('\t');
36 } else if (col == 2) {
37 if (toys.optflags & FLAG_3) return;
38 if (!(toys.optflags & FLAG_1)) putchar('\t');
39 if (!(toys.optflags & FLAG_2)) putchar('\t');
50 if (toys.optflags == 7) return;
52 for (i = 0; i < 2; i++) {
53 file[i] = strcmp("-", toys.optargs[i]) ? xopen(toys.optargs[i], O_RDONLY) : 0;
54 line[i] = get_line(file[i]);
57 while (line[0] && line[1]) {
58 int order = strcmp(line[0], line[1]);
61 writeline(line[0], 2);
62 for (i = 0; i < 2; i++) {
64 line[i] = get_line(file[i]);
67 i = order < 0 ? 0 : 1;
68 writeline(line[i], i);
70 line[i] = get_line(file[i]);
74 /* print rest of the longer file */
75 for (i = line[0] ? 0 : 1; line[i];) {
76 writeline(line[i], i);
78 line[i] = get_line(file[i]);
81 if (CFG_TOYBOX_FREE) for (i = 0; i < 2; i--) xclose(file[i]);