From 62f23c25753db3b522cf9697e2452ae943c56594 Mon Sep 17 00:00:00 2001 From: Steven Baltakatei Sandoval Date: Tue, 7 Mar 2023 21:32:55 +0000 Subject: [PATCH 1/1] feat(unitproc/get_rand_line):Bash script that gets random line --- unitproc/get_rand_line | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100755 unitproc/get_rand_line diff --git a/unitproc/get_rand_line b/unitproc/get_rand_line new file mode 100755 index 0000000..166d419 --- /dev/null +++ b/unitproc/get_rand_line @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Desc: Gets random line from a newline-delimited file +# Usage: get_rand_line [path FILE] +# Version: 0.0.1 + +yell() { echo "$0: $*" >&2; } # print script path and all args to stderr +die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status +must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails +get_rand_line() { + # Input: arg1 : file path + # stdout: random line from input file + # Usage: get_rand_line [path FILE] + # Depends: GNU Coreutils 8.32 (shuf) + + # Check if file + if [[ ! -f "$1" ]]; then die "FATAL:Not a file:$1"; fi; + if [[ $# -ne 1 ]]; then die "FATAL:Incorrect argument count:$1"; fi; + + # Get line count + lc="$(wc -l "$1" | awk '{print $1}')"; + + # Calc random line number (zero-indexed) + ln="$(shuf -i 0-"$((lc - 1))" -n1)"; + + n=0; + while read -r line; do + # Check if line is target line + if [[ $n -eq $ln ]]; then + printf "%s\n" "$line"; # output + fi; + ((n++)); + done < "$1"; +}; # Returns random line from newline-delimited file +main() { + get_rand_line "$@"; +}; + +main "$@"; -- 2.30.2