How do I make a script in BASH that takes random text from a file?

I have a file like:

ahh

BBB

sss

ddd

uh


And I want to make a script in BASH that can take a random line of that text file and return it to me as a variable or something.

I've heard that this can be done with some AWKs. Any ideas?

UPDATE: I am now using this:

shuf -n 1 text.txt

Thank you all for your help!

0


a source to share


4 answers


Please see: read an arbitrary line



+3


a source


I used a script to generate a random string from my quoted 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"

      

+2


a source


I would use sed with the p argument ...

sed -n '43p' 

      

where 43 can be a variable ...

I'm not very good at awk, but I think you could do almost the same thing (however, I don't know if awk has finished ...)

+1


a source


here is bash, without 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"

      

+1


a source







All Articles