:
##########################################################################
# Shellscript:	randfile - print random file name
# Author     :	Heiner Steven <heiner.steven@odn.de>
# Date       :	2001-04-05
# Requires   :	rand
# Category   :	File Utilities
# SCCS-Id.   :	@(#) randfile	1.1 02/04/13
##########################################################################
# Description
#	Shells like the KornShell (ksh), ksh93, and BASH have
#	an RANDOM environment variable that could be used instead
#	of the external "rand" script:
#	    k=`rand $n`
#	can be replaced with
#	    k=`expr $RANDOM % $n + 1`
##########################################################################

PN=`basename "$0"`			# Program name
VER='1.1'

IgnorePattern="SCCS|RCS|CVS"

Usage () {
    echo >&2 "$PN - print random file name, $VER (hs '01)
usage: $PN [-f list] [pattern]"
    exit 1
}

Msg () {
    for MsgLine
    do echo "$PN: $MsgLine" >&2
    done
}

Fatal () { Msg "$@"; exit 1; }

set -- `getopt f:h "$@"` || Usage
[ $# -lt 1 ] && Usage			# "getopt" detected an error

while [ $# -gt 0 ]
do
    case "$1" in
	-f)	FileList=$2; shift;;
	--)	shift; break;;
	-h)	Usage;;
	-*)	Usage;;
	*)	break;;			# First file name
    esac
    shift
done

[ $# -lt 1 ] && set -- ".*"
search=$1; shift

if [ X"$FileList" = X"" ]
then
    # There was no file list specified, so we will create one of our own. The
    # file will be removed automatically after program termination or
    # receiption of a signal:

    FileList=${TMPDIR:=/tmp}/rf$$
    trap 'rm -f "$FileList" >/dev/null 2>&1' 0
    trap "exit 2" 1 2 3 13 15

    find * -type f -print > "$FileList" || exit $?
fi

n=`egrep -v "$IgnorePattern" < "$FileList" | egrep "$search" | wc -l`
k=`rand $n`

egrep -v "$IgnorePattern" < "$FileList" | egrep "$search" |
    sed -n "$k{p;q;}"
