aboutsummaryrefslogtreecommitdiff
path: root/bin/rndl.awk
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/rndl.awk
parentBetter implementation of pks(6df) (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/rndl.awk')
-rw-r--r--bin/rndl.awk29
1 files changed, 29 insertions, 0 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
+}