aboutsummaryrefslogtreecommitdiffstats
path: root/tools/reduce
diff options
context:
space:
mode:
authorJan T <jan@jantuomi.fi>2025-11-13 11:31:30 +0000
committerJan Tuomi <jan@jantuomi.fi>2025-11-13 13:34:38 +0200
commit3df80b5afbebbf3af63b49fe98a3faecd2b68439 (patch)
tree3db37a25de23b7a6b21b3df261b84dc1359c1555 /tools/reduce
Initial commit
Diffstat (limited to 'tools/reduce')
-rwxr-xr-xtools/reduce27
1 files changed, 27 insertions, 0 deletions
diff --git a/tools/reduce b/tools/reduce
new file mode 100755
index 0000000..effb98d
--- /dev/null
+++ b/tools/reduce
@@ -0,0 +1,27 @@
+#!/bin/sh
+
+if [ "$#" -ne 2 ]; then
+ echo "Usage: $0 <init> <expr>"
+ echo ""
+ echo "Run the given command for each newline-separated line in stdin."
+ echo 'The expression computes the next value of "$ACC" (think reduce in many programming languages).'
+ echo 'The initial value of "$ACC" is the first argument to the script.'
+ echo 'The iterator variable is called "$ELEM", and the index variable is called "$IDX".'
+ echo 'The final value of "$ACC" is printed after all lines have been processed.'
+ exit 1
+fi
+
+i=0
+ACC="$1"
+while IFS=$'\n' read -r line; do
+ j=0
+ for item in $line; do
+ eval "X${j}='$item'"
+ j=$((j+1))
+ done
+
+ IDX=$i ELEM="$line" eval "ACC=\"$2\""
+ i=$((i+1))
+done
+
+echo "$ACC"