]> git.draconx.ca Git - dxcommon.git/blobdiff - scripts/join.awk
Add "join" detection macro.
[dxcommon.git] / scripts / join.awk
diff --git a/scripts/join.awk b/scripts/join.awk
new file mode 100755 (executable)
index 0000000..548ca2c
--- /dev/null
@@ -0,0 +1,61 @@
+#!/bin/awk -f
+#
+# Copyright © 2022 Nick Bowler
+#
+# Partial implementation of POSIX "join" command.  No options are supported.
+#
+# License WTFPL2: Do What The Fuck You Want To Public License, version 2.
+# This is free software: you are free to do what the fuck you want to.
+# There is NO WARRANTY, to the extent permitted by law.
+
+BEGIN {
+  if (ARGC != 3) {
+    exit 1;
+  }
+
+  file2 = ARGV[2];
+  delete ARGV[2];
+
+  advance_rhs();
+}
+
+$1 == lhs_prev {
+  # Rewind RHS as we have duplicate keys in LHS.
+  close(file2);
+  advance_rhs();
+}
+
+$1 < rhs[1] { next }
+{
+  while ($1 > rhs[1]) {
+    if (advance_rhs() == 0)
+      exit(0);
+  }
+}
+
+$1 == rhs[1] {
+  lhs_prev = $1 = $1;
+  do {
+    print_match();
+    advance_rhs();
+  } while ($1 == rhs[1]);
+}
+
+function advance_rhs(raw, rc)
+{
+  rc = getline raw < file2;
+  if (rc < 0)
+    exit(1);
+
+  split(raw, rhs);
+  return rc;
+}
+
+function print_match(i)
+{
+  printf "%s", $0
+  for (i = 2; i in rhs; i++) {
+    printf " %s", rhs[i];
+  }
+  print ""
+}