How to do a script in BASH which takes random text from file? [duplicate]
Question
This question already has an answer here:
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!
Solution
Please see: read random line
OTHER TIPS
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"
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...)
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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow