join.c revision 1.11 1 /* $NetBSD: join.c,v 1.11 1997/10/19 03:32:13 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1991 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Steve Hayman of Indiana University, Michiro Hikida and David
9 * Goodenough.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 */
39
40 #include <sys/cdefs.h>
41 #ifndef lint
42 __COPYRIGHT(
43 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
44 All rights reserved.\n");
45 #endif /* not lint */
46
47 #ifndef lint
48 #if 0
49 static char sccsid[] = "from: @(#)join.c 5.1 (Berkeley) 11/18/91";
50 #else
51 __RCSID("$NetBSD: join.c,v 1.11 1997/10/19 03:32:13 lukem Exp $");
52 #endif
53 #endif /* not lint */
54
55 #include <sys/types.h>
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62
63 /*
64 * There's a structure per input file which encapsulates the state of the
65 * file. We repeatedly read lines from each file until we've read in all
66 * the consecutive lines from the file with a common join field. Then we
67 * compare the set of lines with an equivalent set from the other file.
68 */
69 typedef struct {
70 char *line; /* line */
71 u_long linealloc; /* line allocated count */
72 char **fields; /* line field(s) */
73 u_long fieldcnt; /* line field(s) count */
74 u_long fieldalloc; /* line field(s) allocated count */
75 } LINE;
76
77 typedef struct {
78 FILE *fp; /* file descriptor */
79 u_long joinf; /* join field (-1, -2, -j) */
80 int unpair; /* output unpairable lines (-a) */
81 int number; /* 1 for file 1, 2 for file 2 */
82
83 LINE *set; /* set of lines with same field */
84 u_long pushback; /* line on the stack */
85 u_long setcnt; /* set count */
86 u_long setalloc; /* set allocated count */
87 } INPUT;
88 INPUT input1 = { NULL, 0, 0, 1, NULL, -1, 0, 0, },
89 input2 = { NULL, 0, 0, 1, NULL, -1, 0, 0, };
90
91 typedef struct {
92 u_long fileno; /* file number */
93 u_long fieldno; /* field number */
94 } OLIST;
95 OLIST *olist; /* output field list */
96 u_long olistcnt; /* output field list count */
97 u_long olistalloc; /* output field allocated count */
98
99 int joinout = 1; /* show lines with matched join fields (-v) */
100 int needsep; /* need separator character */
101 int spans = 1; /* span multiple delimiters (-t) */
102 char *empty; /* empty field replacement string (-e) */
103 char *tabchar = " \t"; /* delimiter characters (-t) */
104
105 int cmp __P((LINE *, u_long, LINE *, u_long));
106 void enomem __P((void));
107 void fieldarg __P((char *));
108 void joinlines __P((INPUT *, INPUT *));
109 int main __P((int, char **));
110 void obsolete __P((char **));
111 void outfield __P((LINE *, u_long));
112 void outoneline __P((INPUT *, LINE *));
113 void outtwoline __P((INPUT *, LINE *, INPUT *, LINE *));
114 void slurp __P((INPUT *));
115 void usage __P((void));
116
117 int
118 main(argc, argv)
119 int argc;
120 char *argv[];
121 {
122 INPUT *F1, *F2;
123 int aflag, ch, cval, vflag;
124 char *end;
125
126 F1 = &input1;
127 F2 = &input2;
128
129 aflag = vflag = 0;
130 obsolete(argv);
131 while ((ch = getopt(argc, argv, "\01a:e:j:1:2:o:t:v:")) != -1) {
132 switch (ch) {
133 case '\01':
134 aflag = 1;
135 F1->unpair = F2->unpair = 1;
136 break;
137 case '1':
138 if ((F1->joinf = strtol(optarg, &end, 10)) < 1) {
139 warnx("-1 option field number less than 1");
140 usage();
141 }
142 if (*end) {
143 warnx("illegal field number -- %s", optarg);
144 usage();
145 }
146 --F1->joinf;
147 break;
148 case '2':
149 if ((F2->joinf = strtol(optarg, &end, 10)) < 1) {
150 warnx("-2 option field number less than 1");
151 usage();
152 }
153 if (*end) {
154 warnx("illegal field number -- %s", optarg);
155 usage();
156 }
157 --F2->joinf;
158 break;
159 case 'a':
160 aflag = 1;
161 switch(strtol(optarg, &end, 10)) {
162 case 1:
163 F1->unpair = 1;
164 break;
165 case 2:
166 F2->unpair = 1;
167 break;
168 default:
169 warnx("-a option file number not 1 or 2");
170 usage();
171 break;
172 }
173 if (*end) {
174 warnx("illegal file number -- %s", optarg);
175 usage();
176 }
177 break;
178 case 'e':
179 empty = optarg;
180 break;
181 case 'j':
182 if ((F1->joinf = F2->joinf =
183 strtol(optarg, &end, 10)) < 1) {
184 warnx("-j option field number less than 1");
185 usage();
186 }
187 if (*end) {
188 warnx("illegal field number -- %s", optarg);
189 usage();
190 }
191 --F1->joinf;
192 --F2->joinf;
193 break;
194 case 'o':
195 fieldarg(optarg);
196 break;
197 case 't':
198 spans = 0;
199 if (strlen(tabchar = optarg) != 1) {
200 warnx("illegal tab character specification");
201 usage();
202 }
203 break;
204 case 'v':
205 vflag = 1;
206 joinout = 0;
207 switch(strtol(optarg, &end, 10)) {
208 case 1:
209 F1->unpair = 1;
210 break;
211 case 2:
212 F2->unpair = 1;
213 break;
214 default:
215 warnx("-v option file number not 1 or 2");
216 usage();
217 break;
218 }
219 if (*end) {
220 warnx("illegal file number -- %s", optarg);
221 usage();
222 }
223 break;
224 case '?':
225 default:
226 usage();
227 }
228 }
229 argc -= optind;
230 argv += optind;
231
232 if (aflag && vflag)
233 errx(1, "-a and -v options mutually exclusive");
234
235 if (argc != 2)
236 usage();
237
238 /* Open the files; "-" means stdin. */
239 if (!strcmp(*argv, "-"))
240 F1->fp = stdin;
241 else if ((F1->fp = fopen(*argv, "r")) == NULL)
242 err(1, "%s", *argv);
243 ++argv;
244 if (!strcmp(*argv, "-"))
245 F2->fp = stdin;
246 else if ((F2->fp = fopen(*argv, "r")) == NULL)
247 err(1, "%s", *argv);
248 if (F1->fp == stdin && F2->fp == stdin)
249 errx(1, "only one input file may be stdin");
250
251 slurp(F1);
252 slurp(F2);
253 while (F1->setcnt && F2->setcnt) {
254 cval = cmp(F1->set, F1->joinf, F2->set, F2->joinf);
255 if (cval == 0) {
256 /* Oh joy, oh rapture, oh beauty divine! */
257 if (joinout)
258 joinlines(F1, F2);
259 slurp(F1);
260 slurp(F2);
261 } else if (cval < 0) {
262 /* File 1 takes the lead... */
263 if (F1->unpair)
264 joinlines(F1, NULL);
265 slurp(F1);
266 } else {
267 /* File 2 takes the lead... */
268 if (F2->unpair)
269 joinlines(F2, NULL);
270 slurp(F2);
271 }
272 }
273
274 /*
275 * Now that one of the files is used up, optionally output any
276 * remaining lines from the other file.
277 */
278 if (F1->unpair)
279 while (F1->setcnt) {
280 joinlines(F1, NULL);
281 slurp(F1);
282 }
283 if (F2->unpair)
284 while (F2->setcnt) {
285 joinlines(F2, NULL);
286 slurp(F2);
287 }
288 exit(0);
289 }
290
291 void
292 slurp(F)
293 INPUT *F;
294 {
295 LINE *lp, *lastlp;
296 LINE tmp;
297 size_t len;
298 int cnt;
299 char *bp, *fieldp;
300
301 /*
302 * Read all of the lines from an input file that have the same
303 * join field.
304 */
305 F->setcnt = 0;
306 for (lastlp = NULL;; ++F->setcnt, lastlp = lp) {
307 /*
308 * If we're out of space to hold line structures, allocate
309 * more. Initialize the structure so that we know that this
310 * is new space.
311 */
312 if (F->setcnt == F->setalloc) {
313 cnt = F->setalloc;
314 F->setalloc += 100;
315 if ((F->set = realloc(F->set,
316 F->setalloc * sizeof(LINE))) == NULL)
317 enomem();
318 memset(F->set + cnt, 0, 100 * sizeof(LINE *));
319 }
320
321 /*
322 * Get any pushed back line, else get the next line. Allocate
323 * space as necessary. If taking the line from the stack swap
324 * the two structures so that we don't lose the allocated space.
325 * This could be avoided by doing another level of indirection,
326 * but it's probably okay as is.
327 */
328 lp = &F->set[F->setcnt];
329 if (F->pushback != -1) {
330 tmp = F->set[F->setcnt];
331 F->set[F->setcnt] = F->set[F->pushback];
332 F->set[F->pushback] = tmp;
333 F->pushback = -1;
334 continue;
335 }
336 if ((bp = fgetln(F->fp, &len)) == NULL)
337 return;
338 if (lp->linealloc <= len + 1) {
339 if (lp->linealloc == 0)
340 lp->linealloc = 128;
341 while (lp->linealloc <= len + 1)
342 lp->linealloc *= 2;
343
344 if ((lp->line = realloc(lp->line,
345 lp->linealloc * sizeof(char))) == NULL)
346 enomem();
347 }
348 memmove(lp->line, bp, len+1);
349
350 /* Replace trailing newline, if it exists. */
351 if (bp[len - 1] == '\n')
352 lp->line[len - 1] = '\0';
353 else
354 lp->line[len] = '\0';
355 bp = lp->line;
356
357 /* Split the line into fields, allocate space as necessary. */
358 lp->fieldcnt = 0;
359 while ((fieldp = strsep(&bp, tabchar)) != NULL) {
360 if (spans && *fieldp == '\0')
361 continue;
362 if (lp->fieldcnt == lp->fieldalloc) {
363 lp->fieldalloc += 100;
364 if ((lp->fields = realloc(lp->fields,
365 lp->fieldalloc * sizeof(char *))) == NULL)
366 enomem();
367 }
368 lp->fields[lp->fieldcnt++] = fieldp;
369 }
370
371 /* See if the join field value has changed. */
372 if (lastlp != NULL && cmp(lp, F->joinf, lastlp, F->joinf)) {
373 F->pushback = F->setcnt;
374 break;
375 }
376 }
377 }
378
379 int
380 cmp(lp1, fieldno1, lp2, fieldno2)
381 LINE *lp1, *lp2;
382 u_long fieldno1, fieldno2;
383 {
384
385 if (lp1->fieldcnt <= fieldno1)
386 return (lp2->fieldcnt < fieldno2 ? 0 : 1);
387 if (lp2->fieldcnt <= fieldno2)
388 return (-1);
389 return (strcmp(lp1->fields[fieldno1], lp2->fields[fieldno2]));
390 }
391
392 void
393 joinlines(F1, F2)
394 INPUT *F1, *F2;
395 {
396 int cnt1, cnt2;
397
398 /*
399 * Output the results of a join comparison. The output may be from
400 * either file 1 or file 2 (in which case the first argument is the
401 * file from which to output) or from both.
402 */
403 if (F2 == NULL) {
404 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
405 outoneline(F1, &F1->set[cnt1]);
406 return;
407 }
408 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
409 for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
410 outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
411 }
412
413 void
414 outoneline(F, lp)
415 INPUT *F;
416 LINE *lp;
417 {
418 int cnt;
419
420 /*
421 * Output a single line from one of the files, according to the
422 * join rules. This happens when we are writing unmatched single
423 * lines. Output empty fields in the right places.
424 */
425 if (olist)
426 for (cnt = 0; cnt < olistcnt; ++cnt) {
427 if (olist[cnt].fileno == F->number)
428 outfield(lp, olist[cnt].fieldno);
429 }
430 else
431 for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
432 outfield(lp, cnt);
433 (void)printf("\n");
434 if (ferror(stdout))
435 err(1, "stdout");
436 needsep = 0;
437 }
438
439 void
440 outtwoline(F1, lp1, F2, lp2)
441 INPUT *F1, *F2;
442 LINE *lp1, *lp2;
443 {
444 int cnt;
445
446 /* Output a pair of lines according to the join list (if any). */
447 if (olist)
448 for (cnt = 0; cnt < olistcnt; ++cnt)
449 if (olist[cnt].fileno == 1)
450 outfield(lp1, olist[cnt].fieldno);
451 else /* if (olist[cnt].fileno == 2) */
452 outfield(lp2, olist[cnt].fieldno);
453 else {
454 /*
455 * Output the join field, then the remaining fields from F1
456 * and F2.
457 */
458 outfield(lp1, F1->joinf);
459 for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
460 if (F1->joinf != cnt)
461 outfield(lp1, cnt);
462 for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
463 if (F2->joinf != cnt)
464 outfield(lp2, cnt);
465 }
466 (void)printf("\n");
467 if (ferror(stdout))
468 err(1, "stdout");
469 needsep = 0;
470 }
471
472 void
473 outfield(lp, fieldno)
474 LINE *lp;
475 u_long fieldno;
476 {
477 if (needsep++)
478 (void)printf("%c", *tabchar);
479 if (!ferror(stdout))
480 if (lp->fieldcnt < fieldno) {
481 if (empty != NULL)
482 (void)printf("%s", empty);
483 } else {
484 if (*lp->fields[fieldno] == '\0')
485 return;
486 (void)printf("%s", lp->fields[fieldno]);
487 }
488 if (ferror(stdout))
489 err(1, "stdout");
490 }
491
492 /*
493 * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
494 * fields.
495 */
496 void
497 fieldarg(option)
498 char *option;
499 {
500 u_long fieldno;
501 char *end, *token;
502
503 while ((token = strsep(&option, " \t")) != NULL) {
504 if (*token == '\0')
505 continue;
506 if ((token[0] != '1' && token[0] != '2') || token[1] != '.')
507 errx(1, "malformed -o option field");
508 fieldno = strtol(token + 2, &end, 10);
509 if (*end)
510 errx(1, "malformed -o option field");
511 if (fieldno == 0)
512 errx(1, "field numbers are 1 based");
513 if (olistcnt == olistalloc) {
514 olistalloc += 50;
515 if ((olist = realloc(olist,
516 olistalloc * sizeof(OLIST))) == NULL)
517 enomem();
518 }
519 olist[olistcnt].fileno = token[0] - '0';
520 olist[olistcnt].fieldno = fieldno - 1;
521 ++olistcnt;
522 }
523 }
524
525 void
526 obsolete(argv)
527 char **argv;
528 {
529 int len;
530 char **p, *ap, *t;
531
532 while ((ap = *++argv) != NULL) {
533 /* Return if "--". */
534 if (ap[0] == '-' && ap[1] == '-')
535 return;
536 switch (ap[1]) {
537 case 'a':
538 /*
539 * The original join allowed "-a", which meant the
540 * same as -a1 plus -a2. POSIX 1003.2, Draft 11.2
541 * only specifies this as "-a 1" and "a -2", so we
542 * have to use another option flag, one that is
543 * unlikely to ever be used or accidentally entered
544 * on the command line. (Well, we could reallocate
545 * the argv array, but that hardly seems worthwhile.)
546 */
547 if (ap[2] == '\0')
548 ap[1] = '\01';
549 break;
550 case 'j':
551 /*
552 * The original join allowed "-j[12] arg" and "-j arg".
553 * Convert the former to "-[12] arg". Don't convert
554 * the latter since getopt(3) can handle it.
555 */
556 switch(ap[2]) {
557 case '1':
558 if (ap[3] != '\0')
559 goto jbad;
560 ap[1] = '1';
561 ap[2] = '\0';
562 break;
563 case '2':
564 if (ap[3] != '\0')
565 goto jbad;
566 ap[1] = '2';
567 ap[2] = '\0';
568 break;
569 case '\0':
570 break;
571 default:
572 jbad: errx(1, "illegal option -- %s", ap);
573 usage();
574 }
575 break;
576 case 'o':
577 /*
578 * The original join allowed "-o arg arg". Convert to
579 * "-o arg -o arg".
580 */
581 if (ap[2] != '\0')
582 break;
583 for (p = argv + 2; *p; ++p) {
584 if ((p[0][0] != '1' && p[0][0] != '2') ||
585 p[0][1] != '.')
586 break;
587 len = strlen(*p);
588 if (len - 2 != strspn(*p + 2, "0123456789"))
589 break;
590 if ((t = malloc(len + 3)) == NULL)
591 enomem();
592 t[0] = '-';
593 t[1] = 'o';
594 memmove(t + 2, *p, len + 1);
595 *p = t;
596 }
597 argv = p - 1;
598 break;
599 }
600 }
601 }
602
603 void
604 enomem()
605 {
606 errx(1, "no memory");
607 }
608
609 void
610 usage()
611 {
612 (void)fprintf(stderr, "%s%s\n",
613 "usage: join [-a fileno | -v fileno ] [-e string] [-1 field] ",
614 "[-2 field]\n [-o list] [-t char] file1 file2");
615 exit(1);
616 }
617