views:

39

answers:

2

I'm creating a Shell Script, and I have a file like this called expressions.txt:

"Ploink Poink"
"I Need Oil"
"Some Bytes are Missing!"
"Poink Poink"
"Piiiip Beeeep!!"
"Whoops! I'm out of memory!"
"1 + 1 = 3"
"Please fix my bugs!"
"Goeiedag!"
"Hallo!"
"Guten Tag!"
"Hyvää Päivää!"
"Добрый день"
"!สวัสดี"
"Bonjour!"
"!مرحبا"
"!שלום"
"Γειά!"

I have this code in robot.sh:

expressions=( $(cat expressions.txt) )

# Get random expression...
selectedexpression=${expressions[$RANDOM % ${#expressions[@]}]}

# Write to Shell
echo $selectedexpression

However, this splits the file's content by spaces, not by quotes, so the output could be something like "Ploink, Need or fix. But I want the complete sentences. Is there a way to do this? Thanks

Oh, the shell I use is #!/bin/sh.

+1  A: 

This will work with bash, possibly with sh:

OLDIFS="$IFS"
IFS=$'\n'
expressions=()
while read line
do
  expressions=("${expressions[@]}" "$line")
done < expressions.txt
IFS="$OLDIFS"
Ignacio Vazquez-Abrams
A: 

use (g)awk, or nawk on Solaris

awk 'BEGIN{srand() }
{
  lines[++d]=$0    
}END{
  RANDOM = int(1 + rand() * d)
  print lines[RANDOM]
}' expression.txt
ghostdog74