Merge branch 'develop' of https://zdv2.bktei.com/gitweb/BK-2020-03 into develop
[BK-2020-03.git] / unitproc / get_rand_line
CommitLineData
62f23c25
SBS
1#!/usr/bin/env bash
2# Desc: Gets random line from a newline-delimited file
3# Usage: get_rand_line [path FILE]
4# Version: 0.0.1
5
6yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
7die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
8must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
9get_rand_line() {
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)
14
15 # Check if file
16 if [[ ! -f "$1" ]]; then die "FATAL:Not a file:$1"; fi;
17 if [[ $# -ne 1 ]]; then die "FATAL:Incorrect argument count:$1"; fi;
18
19 # Get line count
20 lc="$(wc -l "$1" | awk '{print $1}')";
21
22 # Calc random line number (zero-indexed)
23 ln="$(shuf -i 0-"$((lc - 1))" -n1)";
24
25 n=0;
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
30 fi;
31 ((n++));
32 done < "$1";
33}; # Returns random line from newline-delimited file
34main() {
35 get_rand_line "$@";
36};
37
38main "$@";