Skip to content

Instantly share code, notes, and snippets.

@mfurquimdev
Last active August 6, 2021 13:53
Show Gist options
  • Select an option

  • Save mfurquimdev/d2167d170939d45f942a2e4d97e7e96e to your computer and use it in GitHub Desktop.

Select an option

Save mfurquimdev/d2167d170939d45f942a2e4d97e7e96e to your computer and use it in GitHub Desktop.
Print random range of lines from a file
#!/bin/bash
if [[ -z "$1" ]]; then
# Read shell parameter expansion to understand better what this answer do
# https://stackoverflow.com/a/965072/3832827
# https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
echo "usage: $(basename $0) <file_name> [show_n_lines]";
exit 1;
fi
file_name=$1
show_n_lines=$2
if [[ -z "${show_n_lines}" ]]; then
show_n_lines=$(( $(tput lines) - 4 ))
fi
n_lines=$(wc -l ${file_name} | cut -f 1 -d ' ')
bottom_limit=$(( ${n_lines} + 1 ))
upper_limit=$(( ${bottom_limit} - ${show_n_lines} ))
width=$(( $(tput cols) - 1 ))
random_first_line=$(( $RANDOM % ${upper_limit} ))
random_last_line=$(( ${random_first_line} + ${show_n_lines} ))
cat -n ${file_name} | sed -n "${random_first_line},${random_last_line}p" | cut -c1-${width}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment