#!/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 "$@";