1 /* join - join lines of two files on a common field
2 Copyright (C) 91, 95, 96, 1997, 1998 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 Written by Mike Haertel, mike@gnu.ai.mit.edu. */
22 /* Get isblank from GNU libc. */
28 #include <sys/types.h>
31 #if _LIBC || STDC_HEADERS
32 # define TOLOWER(c) tolower (c)
34 # define TOLOWER(c) (ISUPPER (c) ? tolower (c) : (c))
38 #include "long-options.h"
41 #include "memcasecmp.h"
43 #define join system_join
45 /* Undefine, to avoid warning about redefinition on some systems. */
48 #define min(A, B) ((A) < (B) ? (A) : (B))
49 #define max(A, B) ((A) > (B) ? (A) : (B))
51 /* An element of the list identifying which fields to print for each
55 /* File number: 0, 1, or 2. 0 means use the join field.
56 1 means use the first file argument, 2 the second. */
59 /* Field index (zero-based), specified only when FILE is 1 or 2. */
65 /* A field of a line. */
68 const char *beg; /* First character in field. */
69 size_t len; /* The length of the field. */
72 /* A line read from an input file. Newlines are not stored. */
75 char *beg; /* First character in line. */
76 char *lim; /* Character after last character in line. */
77 int nfields; /* Number of elements in `fields'. */
78 int nfields_allocated; /* Number of elements in `fields'. */
82 /* One or more consecutive lines read from a file that all have the
83 same join field value. */
86 int count; /* Elements used in `lines'. */
87 int alloc; /* Elements allocated in `lines'. */
91 /* The name this program was run with. */
94 /* If nonzero, print unpairable lines in file 1 or 2. */
95 static int print_unpairables_1, print_unpairables_2;
97 /* If nonzero, print pairable lines. */
98 static int print_pairables;
100 /* Empty output field filler. */
101 static char *empty_filler;
103 /* Field to join on. */
104 static int join_field_1, join_field_2;
106 /* List of fields to print. */
107 static struct outlist outlist_head;
109 /* Last element in `outlist', where a new element can be added. */
110 static struct outlist *outlist_end = &outlist_head;
112 /* Tab character separating fields; if this is NUL fields are separated
113 by any nonempty string of white space, otherwise by exactly one
117 /* When using getopt_long_only, no long option can start with
118 a character that is a short option. */
119 static struct option const longopts[] =
121 {"ignore-case", no_argument, NULL, 'i'},
122 {"j", required_argument, NULL, 'j'},
123 {"j1", required_argument, NULL, '1'},
124 {"j2", required_argument, NULL, '2'},
128 /* Used to print non-joining lines */
129 static struct line uni_blank;
131 /* If nonzero, ignore case when comparing join fields. */
132 static int ignore_case;
138 fprintf (stderr, _("Try `%s --help' for more information.\n"),
143 Usage: %s [OPTION]... FILE1 FILE2\n\
147 For each pair of input lines with identical join fields, write a line to\n\
148 standard output. The default join field is the first, delimited\n\
149 by whitespace. When FILE1 or FILE2 (not both) is -, read standard input.\n\
151 -a SIDE print unpairable lines coming from file SIDE\n\
152 -e EMPTY replace missing input fields with EMPTY\n\
153 -i, --ignore-case ignore differences in case when comparing fields\n\
154 -j FIELD (obsolescent) equivalent to `-1 FIELD -2 FIELD'\n\
155 -j1 FIELD (obsolescent) equivalent to `-1 FIELD'\n\
156 -j2 FIELD (obsolescent) equivalent to `-2 FIELD'\n\
157 -o FORMAT obey FORMAT while constructing output line\n\
158 -t CHAR use CHAR as input and output field separator\n\
159 -v SIDE like -a SIDE, but suppress joined output lines\n\
160 -1 FIELD join on this FIELD of file 1\n\
161 -2 FIELD join on this FIELD of file 2\n\
162 --help display this help and exit\n\
163 --version output version information and exit\n\
165 Unless -t CHAR is given, leading blanks separate fields and are ignored,\n\
166 else fields are separated by CHAR. Any FIELD is a field number counted\n\
167 from 1. FORMAT is one or more comma or blank separated specifications,\n\
168 each being `SIDE.FIELD' or `0'. Default FORMAT outputs the join field,\n\
169 the remaining fields from FILE1, the remaining fields from FILE2, all\n\
170 separated by CHAR.\n\
172 puts (_("\nReport bugs to <textutils-bugs@gnu.org>."));
174 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
178 ADD_FIELD (struct line *line, const char *field, size_t len)
180 if (line->nfields >= line->nfields_allocated)
182 line->nfields_allocated = (3 * line->nfields_allocated) / 2 + 1;
183 line->fields = (struct field *) xrealloc ((char *) line->fields,
184 (line->nfields_allocated
185 * sizeof (struct field)));
187 line->fields[line->nfields].beg = field;
188 line->fields[line->nfields].len = len;
192 /* Fill in the `fields' structure in LINE. */
195 xfields (struct line *line)
198 register char *ptr, *lim;
205 /* Skip leading blanks before the first field. */
206 while (ptr < lim && ISSPACE (*ptr))
210 for (i = 0; ptr < lim; ++i)
217 while (ptr < lim && *ptr != tab)
219 ADD_FIELD (line, beg, ptr - beg);
228 while (ptr < lim && !ISSPACE (*ptr))
230 ADD_FIELD (line, beg, ptr - beg);
231 while (ptr < lim && ISSPACE (*ptr))
236 if (ptr > line->beg && ((tab && ISSPACE (ptr[-1])) || ptr[-1] == tab))
238 /* Add one more (empty) field because the last character of the
239 line was a delimiter. */
240 ADD_FIELD (line, NULL, 0);
244 /* Read a line from FP into LINE and split it into fields.
245 Return 0 if EOF, 1 otherwise. */
248 get_line (FILE *fp, struct line *line)
250 static int linesize = 80;
257 ptr = xmalloc (linesize);
259 for (i = 0; (c = getc (fp)) != EOF && c != '\n'; ++i)
264 ptr = xrealloc (ptr, linesize);
269 if (c == EOF && i == 0)
276 line->lim = line->beg + i;
277 line->nfields_allocated = 0;
285 freeline (struct line *line)
287 free ((char *) line->fields);
293 initseq (struct seq *seq)
297 seq->lines = (struct line *) xmalloc (seq->alloc * sizeof (struct line));
300 /* Read a line from FP and add it to SEQ. Return 0 if EOF, 1 otherwise. */
303 getseq (FILE *fp, struct seq *seq)
305 if (seq->count == seq->alloc)
308 seq->lines = (struct line *)
309 xrealloc ((char *) seq->lines, seq->alloc * sizeof (struct line));
312 if (get_line (fp, &seq->lines[seq->count]))
321 delseq (struct seq *seq)
324 for (i = 0; i < seq->count; i++)
325 if (seq->lines[i].beg)
326 freeline (&seq->lines[i]);
327 free ((char *) seq->lines);
330 /* Return <0 if the join field in LINE1 compares less than the one in LINE2;
331 >0 if it compares greater; 0 if it compares equal. */
334 keycmp (struct line *line1, struct line *line2)
336 const char *beg1, *beg2; /* Start of field to compare in each file. */
337 int len1, len2; /* Length of fields to compare. */
340 if (join_field_1 < line1->nfields)
342 beg1 = line1->fields[join_field_1].beg;
343 len1 = line1->fields[join_field_1].len;
351 if (join_field_2 < line2->nfields)
353 beg2 = line2->fields[join_field_2].beg;
354 len2 = line2->fields[join_field_2].len;
363 return len2 == 0 ? 0 : -1;
367 /* Use an if-statement here rather than a function variable to
368 avoid portability hassles of getting a non-conflicting declaration
371 diff = memcasecmp (beg1, beg2, min (len1, len2));
373 diff = memcmp (beg1, beg2, min (len1, len2));
380 /* Print field N of LINE if it exists and is nonempty, otherwise
381 `empty_filler' if it is nonempty. */
384 prfield (int n, struct line *line)
388 if (n < line->nfields)
390 len = line->fields[n].len;
392 fwrite (line->fields[n].beg, 1, len, stdout);
393 else if (empty_filler)
394 fputs (empty_filler, stdout);
396 else if (empty_filler)
397 fputs (empty_filler, stdout);
400 /* Print the join of LINE1 and LINE2. */
403 prjoin (struct line *line1, struct line *line2)
405 const struct outlist *outlist;
407 outlist = outlist_head.next;
410 const struct outlist *o;
420 if (line1 == &uni_blank)
423 field = join_field_2;
428 field = join_field_1;
433 line = (o->file == 1 ? line1 : line2);
434 assert (o->field >= 0);
437 prfield (field, line);
441 putchar (tab ? tab : ' ');
449 if (line1 == &uni_blank)
456 prfield (join_field_1, line1);
457 for (i = 0; i < join_field_1 && i < line1->nfields; ++i)
459 putchar (tab ? tab : ' ');
462 for (i = join_field_1 + 1; i < line1->nfields; ++i)
464 putchar (tab ? tab : ' ');
468 for (i = 0; i < join_field_2 && i < line2->nfields; ++i)
470 putchar (tab ? tab : ' ');
473 for (i = join_field_2 + 1; i < line2->nfields; ++i)
475 putchar (tab ? tab : ' ');
482 /* Print the join of the files in FP1 and FP2. */
485 join (FILE *fp1, FILE *fp2)
487 struct seq seq1, seq2;
489 int diff, i, j, eof1, eof2;
491 /* Read the first line of each file. */
497 while (seq1.count && seq2.count)
499 diff = keycmp (&seq1.lines[0], &seq2.lines[0]);
502 if (print_unpairables_1)
503 prjoin (&seq1.lines[0], &uni_blank);
504 freeline (&seq1.lines[0]);
511 if (print_unpairables_2)
512 prjoin (&uni_blank, &seq2.lines[0]);
513 freeline (&seq2.lines[0]);
519 /* Keep reading lines from file1 as long as they continue to
520 match the current line from file2. */
523 if (!getseq (fp1, &seq1))
529 while (!keycmp (&seq1.lines[seq1.count - 1], &seq2.lines[0]));
531 /* Keep reading lines from file2 as long as they continue to
532 match the current line from file1. */
535 if (!getseq (fp2, &seq2))
541 while (!keycmp (&seq1.lines[0], &seq2.lines[seq2.count - 1]));
545 for (i = 0; i < seq1.count - 1; ++i)
546 for (j = 0; j < seq2.count - 1; ++j)
547 prjoin (&seq1.lines[i], &seq2.lines[j]);
550 for (i = 0; i < seq1.count - 1; ++i)
551 freeline (&seq1.lines[i]);
554 seq1.lines[0] = seq1.lines[seq1.count - 1];
560 for (i = 0; i < seq2.count - 1; ++i)
561 freeline (&seq2.lines[i]);
564 seq2.lines[0] = seq2.lines[seq2.count - 1];
571 if (print_unpairables_1 && seq1.count)
573 prjoin (&seq1.lines[0], &uni_blank);
574 freeline (&seq1.lines[0]);
575 while (get_line (fp1, &line))
577 prjoin (&line, &uni_blank);
582 if (print_unpairables_2 && seq2.count)
584 prjoin (&uni_blank, &seq2.lines[0]);
585 freeline (&seq2.lines[0]);
586 while (get_line (fp2, &line))
588 prjoin (&uni_blank, &line);
597 /* Add a field spec for field FIELD of file FILE to `outlist'. */
600 add_field (int file, int field)
604 assert (file == 0 || file == 1 || file == 2);
605 assert (file == 0 ? field < 0 : field >= 0);
607 o = (struct outlist *) xmalloc (sizeof (struct outlist));
612 /* Add to the end of the list so the fields are in the right order. */
613 outlist_end->next = o;
617 /* Convert a single field specifier string, S, to a *FILE_INDEX, *FIELD_INDEX
618 pair. In S, the field index string is 1-based; *FIELD_INDEX is zero-based.
619 If S is valid, return zero. Otherwise, give a diagnostic, don't update
620 *FILE_INDEX or *FIELD_INDEX, and return nonzero. */
623 decode_field_spec (const char *s, int *file_index, int *field_index)
627 /* The first character must be 0, 1, or 2. */
634 /* Give *field_index an invalid value. */
640 /* `0' must be all alone -- no `.FIELD'. */
641 error (0, 0, _("invalid field specifier: `%s'"), s);
647 if (s[1] == '.' && s[2] != '\0')
652 s_err = xstrtol (s + 2, NULL, 10, &tmp_long, "");
653 if (s_err != LONGINT_OK || tmp_long <= 0 || tmp_long > INT_MAX)
655 error (0, 0, _("invalid field number: `%s'"), s + 2);
659 *file_index = s[0] - '0';
660 /* Convert to a zero-based index. */
661 *field_index = (int) tmp_long - 1;
668 error (0, 0, _("invalid file number in field spec: `%s'"), s);
674 /* Add the comma or blank separated field spec(s) in STR to `outlist'.
675 Return nonzero to indicate failure. */
678 add_field_list (const char *c_str)
682 /* Make a writable copy of c_str. */
683 str = (char *) alloca (strlen (c_str) + 1);
690 int file_index, field_index;
693 p = strpbrk (p, ", \t");
696 invalid = decode_field_spec (spec_item, &file_index, &field_index);
699 add_field (file_index, field_index);
700 uni_blank.nfields = max (uni_blank.nfields, field_index);
706 /* Create a blank line with COUNT fields separated by tabs. */
709 make_blank (struct line *blank, int count)
712 blank->nfields = count;
713 blank->beg = xmalloc (blank->nfields + 1);
714 blank->fields = (struct field *) xmalloc (sizeof (struct field) * count);
715 for (i = 0; i < blank->nfields; i++)
717 blank->beg[i] = '\t';
718 blank->fields[i].beg = &blank->beg[i];
719 blank->fields[i].len = 0;
721 blank->beg[i] = '\0';
722 blank->lim = &blank->beg[i];
726 main (int argc, char **argv)
730 int optc, prev_optc = 0, nfiles;
732 program_name = argv[0];
733 setlocale (LC_ALL, "");
734 bindtextdomain (PACKAGE, LOCALEDIR);
735 textdomain (PACKAGE);
737 /* Initialize this before parsing options. In parsing options,
738 it may be increased. */
739 uni_blank.nfields = 1;
741 parse_long_options (argc, argv, "join", GNU_PACKAGE, VERSION, usage);
746 while ((optc = getopt_long_only (argc, argv, "-a:e:i1:2:o:t:v:", longopts,
761 if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
762 || (val != 1 && val != 2))
763 error (EXIT_FAILURE, 0, _("invalid field number: `%s'"), optarg);
765 print_unpairables_1 = 1;
767 print_unpairables_2 = 1;
771 empty_filler = optarg;
779 if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
780 || val <= 0 || val > INT_MAX)
782 error (EXIT_FAILURE, 0,
783 _("invalid field number for file 1: `%s'"), optarg);
785 join_field_1 = (int) val - 1;
789 if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
790 || val <= 0 || val > INT_MAX)
791 error (EXIT_FAILURE, 0,
792 _("invalid field number for file 2: `%s'"), optarg);
793 join_field_2 = (int) val - 1;
797 if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
798 || val <= 0 || val > INT_MAX)
799 error (EXIT_FAILURE, 0, _("invalid field number: `%s'"), optarg);
800 join_field_1 = join_field_2 = (int) val - 1;
804 if (add_field_list (optarg))
812 case 1: /* Non-option argument. */
813 if (prev_optc == 'o' && optind <= argc - 2)
815 if (add_field_list (optarg))
818 /* Might be continuation of args to -o. */
819 continue; /* Don't change `prev_optc'. */
824 error (0, 0, _("too many non-option arguments"));
827 names[nfiles++] = optarg;
836 /* Now that we've seen the options, we can construct the blank line
838 make_blank (&uni_blank, uni_blank.nfields);
842 error (0, 0, _("too few non-option arguments"));
846 fp1 = STREQ (names[0], "-") ? stdin : fopen (names[0], "r");
848 error (EXIT_FAILURE, errno, "%s", names[0]);
849 fp2 = STREQ (names[1], "-") ? stdin : fopen (names[1], "r");
851 error (EXIT_FAILURE, errno, "%s", names[1]);
853 error (EXIT_FAILURE, errno, _("both files cannot be standard input"));
856 if (fp1 != stdin && fclose (fp1) == EOF)
857 error (EXIT_FAILURE, errno, "%s", names[0]);
858 if (fp2 != stdin && fclose (fp2) == EOF)
859 error (EXIT_FAILURE, errno, "%s", names[1]);
860 if ((fp1 == stdin || fp2 == stdin) && fclose (stdin) == EOF)
861 error (EXIT_FAILURE, errno, "-");
862 if (ferror (stdout) || fclose (stdout) == EOF)
863 error (EXIT_FAILURE, errno, _("write error"));