I recently came across a situation where i had to perform certain task on a random file ( of particular extension ) picked up from a directory structure. My OS was linux and so i went for Bash !

I played with some known ( to me, obviously ) commands from my PS1 prompt before i nailed it down.

SearchFolder=”/home/sai/cPrograms”
NumberOfcFiles=`find $SearchFolder -iname “*.c” | wc -l`
rNumber=$[ ( $RANDOM % $NumberOfcFiles ) + 1 ]
rFile=`find $SearchFolder -iname “*.c” | sed -n “$rNumber p”`
ls $rFile

Line by Line Logic

SearchFolder=”/home/sai/cPrograms”

This sets the parent folder of the directory tree to be searched, i.e the scan starts from this directory and prgresses inward.

NumberOfcFiles=`find $SearchFolder -iname “*.c” | wc -l`

Variable NumberOfcFiles speaks for itself. find makes a list of .c files and “wc -l” counts them for me.

rNumber=$[ ( $RANDOM % $NumberOfcFiles ) + 1 ]

$RANDOM is a bash variable that throws pseudo random numbers every time its called ( Thanks to BASH again ! ). RightHandSide of the above code is to obtain a random number within the 1-$NumberOfcFiles range. i.e if there are 100 files, rNumber will be a random number with in the range 1 – 100.

rFile=`find $SearchFolder -iname “*.c” | sed -n “$rNumber p”`
ls $rFile

This simply picks $rNumber th file from the “find” list and ls prints it on your screen.

Wasn’t that fun ??

VN:F [1.9.6_1107]
Rating: 8.3/10 (3 votes cast)
VN:F [1.9.6_1107]
Rating: +3 (from 3 votes)
Fun with Bash Scripting, 8.3 out of 10 based on 3 ratings
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Live
  • StumbleUpon
  • Twitter
  • Yahoo! Buzz
  • Reddit
  • Technorati