2 * Copyright (c) 1991, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Steve Hayman of the Computer Science Department, Indiana University,
7 * Michiro Hikida and David Goodenough.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 static const char copyright[] =
36 "@(#) Copyright (c) 1991, 1993, 1994\n\
37 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid[] = "@(#)join.c 8.6 (Berkeley) 5/4/95";
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
61 * There's a structure per input file which encapsulates the state of the
62 * file. We repeatedly read lines from each file until we've read in all
63 * the consecutive lines from the file with a common join field. Then we
64 * compare the set of lines with an equivalent set from the other file.
67 char *line; /* line */
68 u_long linealloc; /* line allocated count */
69 char **fields; /* line field(s) */
70 u_long fieldcnt; /* line field(s) count */
71 u_long fieldalloc; /* line field(s) allocated count */
75 FILE *fp; /* file descriptor */
76 u_long joinf; /* join field (-1, -2, -j) */
77 int unpair; /* output unpairable lines (-a) */
78 u_long number; /* 1 for file 1, 2 for file 2 */
80 LINE *set; /* set of lines with same field */
81 int pushbool; /* if pushback is set */
82 u_long pushback; /* line on the stack */
83 u_long setcnt; /* set count */
84 u_long setalloc; /* set allocated count */
86 static INPUT input1 = { NULL, 0, 0, 1, NULL, 0, 0, 0, 0 },
87 input2 = { NULL, 0, 0, 2, NULL, 0, 0, 0, 0 };
90 u_long filenum; /* file number */
91 u_long fieldno; /* field number */
93 static OLIST *olist; /* output field list */
94 static u_long olistcnt; /* output field list count */
95 static u_long olistalloc; /* output field allocated count */
97 static int joinout = 1; /* show lines with matched join fields (-v) */
98 static int needsep; /* need separator character */
99 static int spans = 1; /* span multiple delimiters (-t) */
100 static char *empty; /* empty field replacement string (-e) */
101 static wchar_t default_tabchar[] = L" \t";
102 static wchar_t *tabchar = default_tabchar; /* delimiter characters (-t) */
104 static int cmp(LINE *, u_long, LINE *, u_long);
105 static void fieldarg(char *);
106 static void joinlines(INPUT *, INPUT *);
107 static int mbscoll(const char *, const char *);
108 static char *mbssep(char **, const wchar_t *);
109 static void obsolete(char **);
110 static void outfield(LINE *, u_long, int);
111 static void outoneline(INPUT *, LINE *);
112 static void outtwoline(INPUT *, LINE *, INPUT *, LINE *);
113 static void slurp(INPUT *);
114 static wchar_t *towcs(const char *);
115 static void usage(void);
118 main(int argc, char *argv[])
121 int aflag, ch, cval, vflag;
124 setlocale(LC_ALL, "");
131 while ((ch = getopt(argc, argv, "\01a:e:j:1:2:o:t:v:")) != -1) {
133 case '\01': /* See comment in obsolete(). */
135 F1->unpair = F2->unpair = 1;
138 if ((F1->joinf = strtol(optarg, &end, 10)) < 1)
139 errx(1, "-1 option field number less than 1");
141 errx(1, "illegal field number -- %s", optarg);
145 if ((F2->joinf = strtol(optarg, &end, 10)) < 1)
146 errx(1, "-2 option field number less than 1");
148 errx(1, "illegal field number -- %s", optarg);
153 switch(strtol(optarg, &end, 10)) {
161 errx(1, "-a option file number not 1 or 2");
165 errx(1, "illegal file number -- %s", optarg);
171 if ((F1->joinf = F2->joinf =
172 strtol(optarg, &end, 10)) < 1)
173 errx(1, "-j option field number less than 1");
175 errx(1, "illegal field number -- %s", optarg);
184 if (mbrtowc(&tabchar[0], optarg, MB_LEN_MAX, NULL) !=
186 errx(1, "illegal tab character specification");
192 switch (strtol(optarg, &end, 10)) {
200 errx(1, "-v option file number not 1 or 2");
204 errx(1, "illegal file number -- %s", optarg);
215 errx(1, "the -a and -v options are mutually exclusive");
220 /* Open the files; "-" means stdin. */
221 if (!strcmp(*argv, "-"))
223 else if ((F1->fp = fopen(*argv, "r")) == NULL)
226 if (!strcmp(*argv, "-"))
228 else if ((F2->fp = fopen(*argv, "r")) == NULL)
230 if (F1->fp == stdin && F2->fp == stdin)
231 errx(1, "only one input file may be stdin");
235 while (F1->setcnt && F2->setcnt) {
236 cval = cmp(F1->set, F1->joinf, F2->set, F2->joinf);
238 /* Oh joy, oh rapture, oh beauty divine! */
243 } else if (cval < 0) {
244 /* File 1 takes the lead... */
249 /* File 2 takes the lead... */
257 * Now that one of the files is used up, optionally output any
258 * remaining lines from the other file.
276 LINE *lp, *lastlp, tmp;
282 * Read all of the lines from an input file that have the same
286 for (lastlp = NULL;; ++F->setcnt) {
288 * If we're out of space to hold line structures, allocate
289 * more. Initialize the structure so that we know that this
292 if (F->setcnt == F->setalloc) {
295 if ((F->set = realloc(F->set,
296 F->setalloc * sizeof(LINE))) == NULL)
298 memset(F->set + cnt, 0, 50 * sizeof(LINE));
300 /* re-set lastlp in case it moved */
302 lastlp = &F->set[F->setcnt - 1];
306 * Get any pushed back line, else get the next line. Allocate
307 * space as necessary. If taking the line from the stack swap
308 * the two structures so that we don't lose space allocated to
309 * either structure. This could be avoided by doing another
310 * level of indirection, but it's probably okay as is.
312 lp = &F->set[F->setcnt];
314 lastlp = &F->set[F->setcnt - 1];
316 tmp = F->set[F->setcnt];
317 F->set[F->setcnt] = F->set[F->pushback];
318 F->set[F->pushback] = tmp;
322 if ((bp = fgetln(F->fp, &len)) == NULL)
324 if (lp->linealloc <= len + 1) {
325 lp->linealloc += MAX(100, len + 1 - lp->linealloc);
327 realloc(lp->line, lp->linealloc)) == NULL)
330 memmove(lp->line, bp, len);
332 /* Replace trailing newline, if it exists. */
333 if (bp[len - 1] == '\n')
334 lp->line[len - 1] = '\0';
336 lp->line[len] = '\0';
339 /* Split the line into fields, allocate space as necessary. */
341 while ((fieldp = mbssep(&bp, tabchar)) != NULL) {
342 if (spans && *fieldp == '\0')
344 if (lp->fieldcnt == lp->fieldalloc) {
345 lp->fieldalloc += 50;
346 if ((lp->fields = realloc(lp->fields,
347 lp->fieldalloc * sizeof(char *))) == NULL)
350 lp->fields[lp->fieldcnt++] = fieldp;
353 /* See if the join field value has changed. */
354 if (lastlp != NULL && cmp(lp, F->joinf, lastlp, F->joinf)) {
356 F->pushback = F->setcnt;
363 mbssep(char **stringp, const wchar_t *delim)
366 const wchar_t *spanp;
370 if ((s = *stringp) == NULL)
373 n = mbrtowc(&c, s, MB_LEN_MAX, NULL);
374 if (n == (size_t)-1 || n == (size_t)-2)
375 errc(1, EILSEQ, NULL); /* XXX */
379 if ((sc = *spanp++) == c) {
392 cmp(LINE *lp1, u_long fieldno1, LINE *lp2, u_long fieldno2)
394 if (lp1->fieldcnt <= fieldno1)
395 return (lp2->fieldcnt <= fieldno2 ? 0 : 1);
396 if (lp2->fieldcnt <= fieldno2)
398 return (mbscoll(lp1->fields[fieldno1], lp2->fields[fieldno2]));
402 mbscoll(const char *s1, const char *s2)
408 return (strcoll(s1, s2));
409 if ((w1 = towcs(s1)) == NULL || (w2 = towcs(s2)) == NULL)
410 err(1, NULL); /* XXX */
411 ret = wcscoll(w1, w2);
423 if ((n = mbsrtowcs(NULL, &s, 0, NULL)) == (size_t)-1)
425 if ((wcs = malloc((n + 1) * sizeof(*wcs))) == NULL)
427 mbsrtowcs(wcs, &s, n + 1, NULL);
432 joinlines(INPUT *F1, INPUT *F2)
437 * Output the results of a join comparison. The output may be from
438 * either file 1 or file 2 (in which case the first argument is the
439 * file from which to output) or from both.
442 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
443 outoneline(F1, &F1->set[cnt1]);
446 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
447 for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
448 outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
452 outoneline(INPUT *F, LINE *lp)
457 * Output a single line from one of the files, according to the
458 * join rules. This happens when we are writing unmatched single
459 * lines. Output empty fields in the right places.
462 for (cnt = 0; cnt < olistcnt; ++cnt) {
463 if (olist[cnt].filenum == (unsigned)F->number)
464 outfield(lp, olist[cnt].fieldno, 0);
465 else if (olist[cnt].filenum == 0)
466 outfield(lp, F->joinf, 0);
471 for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
472 outfield(lp, cnt, 0);
480 outtwoline(INPUT *F1, LINE *lp1, INPUT *F2, LINE *lp2)
484 /* Output a pair of lines according to the join list (if any). */
486 for (cnt = 0; cnt < olistcnt; ++cnt)
487 if (olist[cnt].filenum == 0) {
488 if (lp1->fieldcnt >= F1->joinf)
489 outfield(lp1, F1->joinf, 0);
491 outfield(lp2, F2->joinf, 0);
492 } else if (olist[cnt].filenum == 1)
493 outfield(lp1, olist[cnt].fieldno, 0);
494 else /* if (olist[cnt].filenum == 2) */
495 outfield(lp2, olist[cnt].fieldno, 0);
498 * Output the join field, then the remaining fields from F1
501 outfield(lp1, F1->joinf, 0);
502 for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
503 if (F1->joinf != cnt)
504 outfield(lp1, cnt, 0);
505 for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
506 if (F2->joinf != cnt)
507 outfield(lp2, cnt, 0);
516 outfield(LINE *lp, u_long fieldno, int out_empty)
519 (void)printf("%lc", (wint_t)*tabchar);
520 if (!ferror(stdout)) {
521 if (lp->fieldcnt <= fieldno || out_empty) {
523 (void)printf("%s", empty);
525 if (*lp->fields[fieldno] == '\0')
527 (void)printf("%s", lp->fields[fieldno]);
535 * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
539 fieldarg(char *option)
541 u_long fieldno, filenum;
544 while ((token = strsep(&option, ", \t")) != NULL) {
548 filenum = fieldno = 0;
549 else if ((token[0] == '1' || token[0] == '2') &&
551 filenum = token[0] - '0';
552 fieldno = strtol(token + 2, &end, 10);
554 errx(1, "malformed -o option field");
556 errx(1, "field numbers are 1 based");
559 errx(1, "malformed -o option field");
560 if (olistcnt == olistalloc) {
562 if ((olist = realloc(olist,
563 olistalloc * sizeof(OLIST))) == NULL)
566 olist[olistcnt].filenum = filenum;
567 olist[olistcnt].fieldno = fieldno;
573 obsolete(char **argv)
578 while ((ap = *++argv) != NULL) {
579 /* Return if "--". */
580 if (ap[0] == '-' && ap[1] == '-')
582 /* skip if not an option */
588 * The original join allowed "-a", which meant the
589 * same as -a1 plus -a2. POSIX 1003.2, Draft 11.2
590 * only specifies this as "-a 1" and "a -2", so we
591 * have to use another option flag, one that is
592 * unlikely to ever be used or accidentally entered
593 * on the command line. (Well, we could reallocate
594 * the argv array, but that hardly seems worthwhile.)
596 if (ap[2] == '\0' && (argv[1] == NULL ||
597 (strcmp(argv[1], "1") != 0 &&
598 strcmp(argv[1], "2") != 0))) {
600 warnx("-a option used without an argument; "
601 "reverting to historical behavior");
606 * The original join allowed "-j[12] arg" and "-j arg".
607 * Convert the former to "-[12] arg". Don't convert
608 * the latter since getopt(3) can handle it.
626 jbad: errx(1, "illegal option -- %s", ap);
632 * The original join allowed "-o arg arg".
633 * Convert to "-o arg -o arg".
637 for (p = argv + 2; *p; ++p) {
638 if (p[0][0] == '0' || ((p[0][0] != '1' &&
639 p[0][0] != '2') || p[0][1] != '.'))
642 if (len - 2 != strspn(*p + 2, "0123456789"))
644 if ((t = malloc(len + 3)) == NULL)
648 memmove(t + 2, *p, len + 1);
660 (void)fprintf(stderr, "%s %s\n%s\n",
661 "usage: join [-a fileno | -v fileno ] [-e string] [-1 field]",
663 " [-o list] [-t char] file1 file2");