Link to home
Start Free TrialLog in
Avatar of DSwiftie
DSwiftie

asked on

Pick a random word from a file UNIX

nice easy question for u smart lot how do u pick a random word from a file that is in the formart of

word1
word2
word3
word4
word5
?
Avatar of Dozer42
Dozer42

perl -e 'open IN, "<FILENAME";rand($.) < 1 && ($n=$_) while <IN>;print $n'
Avatar of Tintin
#!/usr/bin/bash
file=/path/to/file
lines=`wc -l <$file
n=$RANDOM
let "n %= $lines"
sed -n ${n}p $file
perl -ne '$n=$_ if rand $.<1;END{print $n}' filename
perl -MTie::File -le 'tie @a,"Tie::File", "filename"; print @a[rand @a]'
awk 'rand<1/NR{n=$0}END{print n}' < filename
perl -e '@a=<>;print$a[rand@a]' filename


Avatar of DSwiftie

ASKER

i know using sed or perlor awk is well worth knowin but tryn to avoid using those tools
What tools would you prefer to use?
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ozo thanx again m8 allways spot on. Thankyou all for the help well apriaciated
On large files, ozo's solution will be *much* slower than my bash solution.
It's slower by about the same factor on small files too.

But there seemed to be an inexplicable desire to avoid sed.
We could have used head|tail instead, but  I didn't know if those were to be avoided too.
We could have implemented the sed function in pure bash, which would have simplified the while loop slightly, but that could still leave the wc
reimplementing wc in pure bash could mean two loops, and it seemed simpler to do it in one
even if there is a performance penalty, which might depend on the implementation.


i can't explain sed thats y i dont use it doing tutorial on using sed and awk now but for now can't xplain myself when using it so am tryin to keep everything at a level i can understand.