views:

454

answers:

4

I have file like:

aaa

bbb

ccc

ddd

eee


And I want to do a script in BASH which can takes random line of this text file, and return it to me as variable or something.

I hear it can be done with some AWK. Any ideas?

UPDATE: I now using this:

shuf -n 1 text.txt

Thanks you all for help!

+2  A: 

Please see: read random line

ennuikiller
+2  A: 

I used a script like this to generate a random line from my singature-quotes file:

#!/bin/bash

QUOTES_FILE=$HOME/.quotes/quotes.txt
numLines=`wc -l $QUOTES_FILE | cut -d" " -f 1`

random=`date +%N`

selectedLineNumber=$(($random - $($random/$numLines) * $numLines + 1))
selectedLine=`head -n $selectedLineNumber $QUOTES_FILE | tail -n 1`

echo -e "$selectedLine"
kender
+1 I was just typing in pretty much exactly that solution although I would probably have printed the selected line using sed -n "$selectedLineNumber/p"
Steve Weet
Would be probably better, but I have this script for ages there and I'm pretty sure back when I wrote it, I suppose I didn't know much 'bout sed.
kender
A: 

I would use sed with p argument...

sed -n '43p'

where 43 could be a variable ...

i don't know much about awk but i guess you could do almost the same thing (however i don't know if awk is turing complete...)

LB
A: 

here's a bash way, w/o any external tools

IFS=$'\n'
set -- $(<"myfile")
len=${#@}
rand=$((RANDOM%len+1))
linenum=0
while read -r myline
do
  (( linenum++ ))
  case "$linenum" in
   $rand) echo "$myline";;
  esac
done <"myfile"