aboutsummaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2017-07-01 21:49:27 +1200
committerTom Ryder <tom@sanctum.geek.nz>2017-07-01 22:00:07 +1200
commit7adef2006aaff89db93c87fd1470a688fb1d4907 (patch)
tree25e967034dad315ca11b50b51b2d1088c65eaf00 /bin
parentdbc1be0317ad5e70afb895648f4d6c8f0fbc1080 (diff)
downloaddotfiles-7adef2006aaff89db93c87fd1470a688fb1d4907.tar.gz
dotfiles-7adef2006aaff89db93c87fd1470a688fb1d4907.zip
Reimplement rndl(1df) in Awk
Removes the need for the temporary file. Also refactor pks(6df) to accommodate it.
Diffstat (limited to 'bin')
-rw-r--r--bin/rndl.awk29
-rw-r--r--bin/rndl.mi538
2 files changed, 29 insertions, 38 deletions
diff --git a/bin/rndl.awk b/bin/rndl.awk
new file mode 100644
index 00000000..8359af90
--- /dev/null
+++ b/bin/rndl.awk
@@ -0,0 +1,29 @@
+# Print a random line from input
+
+# Process arguments
+BEGIN {
+
+ # Name self
+ self = "rndl"
+
+ # Seed the random number generator
+ "rnds 2>/dev/null" | getline seed
+ srand(seed)
+}
+
+# Iterate over the lines, randomly assigning the first field of each one with a
+# decreasing probability
+rand() * NR < 1 { ln = $0 }
+
+# Check and print
+END {
+
+ # Check that we processed at least one line
+ if (!NR) {
+ printf "%s: No lines found on input\n", self | "cat >&2"
+ exit(1)
+ }
+
+ # Print the line
+ print ln
+}
diff --git a/bin/rndl.mi5 b/bin/rndl.mi5
deleted file mode 100644
index f99ccbea..00000000
--- a/bin/rndl.mi5
+++ /dev/null
@@ -1,38 +0,0 @@
-# Print a random line from input
-self=rndl
-
-# If there are no arguments, we're checking stdin; this is more complicated
-# than checking file arguments because we have to count the lines in order to
-# correctly choose a random one, and two passes means we require a temporary
-# file if we don't want to read all of the input into memory (!)
-if [ "$#" -eq 0 ] ; then
-
-<%
-include(`include/mktd.m4')
-%>
-
- # We'll operate on stdin in the temp directory; write the script's stdin to
- # it with cat(1)
- set -- "$td"/stdin
- cat >"$td"/stdin
-fi
-
-# Count the number of lines in the input
-lc=$(sed -- '$=;d' "$@") || exit
-
-# If there were none, bail
-case $lc in
- ''|0)
- printf >&2 'rndl: No lines found on input\n'
- exit 2
- ;;
-esac
-
-# Try to get a random seed from rnds(1df) for rndi(1df)
-seed=$(rnds)
-
-# Get a random line number from rndi(1df)
-ri=$(rndi 1 "$lc" "$seed") || exit
-
-# Print the line using sed(1)
-sed -- "$ri"'!d' "$@"