#! /bin/bash # Script to print "some" lines of a file, like head or tail but, random start # # Usage: some [[-#] FILE] # Helper functions PROG=`basename "$0" | tr -d '\n'` function info() { echo ${PROG}\: info: "$@" 1>&2; } function warn() { echo ${PROG}\: warning: "$@" 1>&2; } function error() { echo ${PROG}\: error: "$@" 1>&2; } function debug() { [[ -v DEBUG ]] && echo ${PROG}\: debug: "$@" 1>&2 || true ; } function die() { echo ${PROG}\: fatal: "$@" 1>&2 && exit 1; } function someFunc { # Functon to print "some" lines of a file, like head or tail but, random start # # ARGS: # # $1 - "-#" or FILENAME if only one arg # $2 - FILENAME if present set -e; set -u; set -o pipefail # be safe out there HOW_MANY=10 # Number of lines to print. Default. FILE="/dev/stdin" # default SOMELOG=${HOME}/.somelog # log of queries in case you want to find that chunk again MAXLOG=10 if [ "$#" -eq 0 ]; then : elif [ "$#" -eq 1 ]; then if [[ "$1" =~ -[0-9] ]]; then HOW_MANY=`echo "$1" | sed 's/^-//'` else FILE="$1" fi elif [ "$#" -eq 2 ]; then if [[ "$1" =~ -[0-9] ]]; then HOW_MANY=`echo "$1" | sed 's/^-//'` else echo "some: Usage: some [-# [FILE]]" return fi FILE="$2" fi # Count the lines to bound display LINES=`wc -l $FILE | sed -e 's/ .*//'` # pick a random starting line at least HOW_MANY back from the end FIRST=$((1 + RANDOM % (LINES - HOW_MANY + 1 ))) FIRST=$((FIRST>LINES ? LINES : FIRST)) LAST=$((FIRST + HOW_MANY - 1)) LAST=$((LAST>LINES ? LINES : LAST)) # display line numbers to stderr to allow re-extraction of randomly chosen lines echo some: lines $FIRST to $LAST \(of $LINES\) of $FILE |& tee /dev/stderr >> ${SOMELOG} # only keep MAXLOG lines of SOMELOG mv ${SOMELOG} ${SOMELOG}.$$ && tail -${MAXLOG} ${SOMELOG}.$$ > ${SOMELOG} && rm ${SOMELOG}.$$ # Let's see some lines ! awk "NR >= $FIRST && NR <= $LAST" $FILE } someFunc $*