From be0d368c65824d52a20517e5fcde692f65dce332 Mon Sep 17 00:00:00 2001 From: Ben Hoyt Date: Sat, 28 May 2022 13:44:14 +1200 Subject: [PATCH] Add library of helper functions (mainly for CSV processing/creation) --- lib.awk | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 lib.awk diff --git a/lib.awk b/lib.awk new file mode 100644 index 00000000..d38c9006 --- /dev/null +++ b/lib.awk @@ -0,0 +1,75 @@ + +# TODO: add tests for these + +# Set fields from array a according to the order in OFIELDS, which must have +# field numbers as keys (from 1 to N) and field names as values, for example +# OFIELDS[1] = "name"; OFIELDS[2] = "age". +function setfields(a, i) { + for (i=1; i in OFIELDS; i++) { + $i = a[OFIELDS[i]] + } + NF = i-1 +} + +# Call setfields(a) and then print the current row. +function printfields(a) { + setfields(a) + print +} + +# Print the header (field names) from OFIELDS +function printheader( i) { + for (i=1; i in OFIELDS; i++) { + $i = OFIELDS[i] + } + NF = i-1 + print +} + +# Delete the nth field from $0. If num is given, delete num fields starting +# from the nth field. +function delfield(n, num, i) { + if (n < 1 || n > NF || num < 0) { + $1 = $1 # ensure $0 gets rewritten + return + } + if (num == 0) { + num = 1 + } + if (num > NF-n+1) { + num = NF-n+1 + } + for (i=n; i<=NF-num; i++) { + $i = $(i+num) + } + NF -= num +} + +# Insert a new empty field just before the nth field in $0. If num is given, +# insert num empty fields just before the nth field. +function insfield(n, num, i) { + if (n < 1 || num < 0) { + $1 = $1 # ensure $0 gets rewritten + return + } + if (num == 0) { + num = 1 + } + for (i=NF; i>=n; i--) { + $(i+num) = $i + } + for (i=n; i