]>
zdv2.bktei.com Git - BK-2020-03.git/blob - unitproc/get_rand_line
   2 # Desc: Gets random line from a newline-delimited file 
   3 # Usage: get_rand_line [path FILE] 
   6 yell
() { echo "$0: $*" >&2; } # print script path and all args to stderr 
   7 die
() { yell 
"$*"; exit 111; } # same as yell() but non-zero exit status 
   8 must
() { "$@" || die 
"cannot $*"; } # runs args as command, reports args if command fails 
  10     # Input: arg1 : file path 
  11     #        stdout: random line from input file 
  12     # Usage: get_rand_line [path FILE] 
  13     # Depends: GNU Coreutils 8.32 (shuf) 
  16     if [[ ! -f "$1" ]]; then die 
"FATAL:Not a file:$1"; fi; 
  17     if [[ $# -ne 1 ]]; then die 
"FATAL:Incorrect argument count:$1"; fi; 
  20     lc
="$(wc -l "$1" | awk '{print $1}')"; 
  22     # Calc random line number (zero-indexed) 
  23     ln="$(shuf -i 0-"$
((lc 
- 1))" -n1)"; 
  26     while read -r line
; do 
  27         # Check if line is target line 
  28         if [[ $n -eq $ln ]]; then 
  29             printf "%s\n" "$line"; # output 
  33 }; # Returns random line from newline-delimited file