]> git.draconx.ca Git - dxcommon.git/blob - scripts/join.awk
548ca2cd3fe955c2674d34b767d6e071cb6a87c7
[dxcommon.git] / scripts / join.awk
1 #!/bin/awk -f
2 #
3 # Copyright © 2022 Nick Bowler
4 #
5 # Partial implementation of POSIX "join" command.  No options are supported.
6 #
7 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
8 # This is free software: you are free to do what the fuck you want to.
9 # There is NO WARRANTY, to the extent permitted by law.
10
11 BEGIN {
12   if (ARGC != 3) {
13     exit 1;
14   }
15
16   file2 = ARGV[2];
17   delete ARGV[2];
18
19   advance_rhs();
20 }
21
22 $1 == lhs_prev {
23   # Rewind RHS as we have duplicate keys in LHS.
24   close(file2);
25   advance_rhs();
26 }
27
28 $1 < rhs[1] { next }
29 {
30   while ($1 > rhs[1]) {
31     if (advance_rhs() == 0)
32       exit(0);
33   }
34 }
35
36 $1 == rhs[1] {
37   lhs_prev = $1 = $1;
38   do {
39     print_match();
40     advance_rhs();
41   } while ($1 == rhs[1]);
42 }
43
44 function advance_rhs(raw, rc)
45 {
46   rc = getline raw < file2;
47   if (rc < 0)
48     exit(1);
49
50   split(raw, rhs);
51   return rc;
52 }
53
54 function print_match(i)
55 {
56   printf "%s", $0
57   for (i = 2; i in rhs; i++) {
58     printf " %s", rhs[i];
59   }
60   print ""
61 }