开发者

Read a file's content (with spaces) into an array

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 开发者_JAVA百科is #!/bin/sh.


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"


use (g)awk, or nawk on Solaris

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜