0

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!

lauriys
  • 4,652
  • 7
  • 32
  • 40

3 Answers3

2

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
  • 85,663
  • 26
  • 103
  • 145
  • +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 May 26 '09 at 13:09
  • 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 May 26 '09 at 13:12
1

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"
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
1

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...)

LB40
  • 12,041
  • 17
  • 72
  • 107