Read random line from a text file

I have a text file with hundreds of lines, i wish to run a script and reads a random line to pass it to another command line such as:

for line in `cat file |grep random line`; do echo $line |mail my@example.com ; done

thank you

Sounds like homework/classroom stuff. This kind of questions are not allowed in here.

The UNIX and Linux Forums - Forum Rules

Read (6) for how to post homework stuff.

hehe not classroom check my IP i'm working at office :slight_smile:

---------- Post updated 09-25-09 at 01:43 AM ---------- Previous update was 09-24-09 at 06:17 PM ----------

google answered me, i don't know why people start not to help each others anymore on forums, it seems forums gonna eventually die like IRC channels when it was so popular in 90s :slight_smile:

#!/bin/sh

LINES=`wc -l $1 | awk '{ print ($1 + 1) }'`
RANDSEED=`date '+%S%M%I'`
LINE=`cat $1 | awk -v COUNT=$LINES -v SEED=$RANDSEED 'BEGIN { srand(SEED); \
i=int(rand()*COUNT) } FNR==i { print $0 }'`
echo $LINE

save it into rand.sh for example then chmod + rand.sh and then ./rand.sh text_file_goes_here and it will do the magic

"Share The Knowledge"
-Unknown

That there is no helping here in the forum is not true and can easily be checked by other threads in here (if you meant this one). Just check - there are other threads but your's that usually get plenty of answers. So really no reason to be insulted.
Also you can't totally deny that the request to read a random line from a text file does sound like homework.
If I were sure it was homework I had closed it already. Mods are only humans too and humans can be wrong. So get over it :wink: And no, I don't start checking people's IPs to get a clue where they work.

sorry if i sounded offensive :slight_smile: but forums are places to share knowledge

good luck :slight_smile:

Interesting post about RANDSEED. Not seen that before.

There's no need for awk:

LINES=$(( $(wc -l < "$1") + 1 ))
awk 'BEGIN { srand() }
{ l[NR]=$0 }
END { print l[int(rand() * NR + 1)] }' "$file"