BASH-file.txt中的正则表达式匹配行具有多个定界符 [英] BASH - Regex match line in file.txt with more than one delimiter
问题描述
早上好!
我正试图让我的脚本读取用户输入,匹配file.txt中的关键字,并基于该匹配返回一个随机的定界响应.我可以匹配关键字并返回一个响应,但是我无法解决如何随机分配多个可能的响应的问题.
I'm trying to get my script to read user input, match a keyword in file.txt and return a random delimited response based on that match. I can match the keyword and return ONE response, but I can't wrap my head around how to randomize a number of possible responses.
例如,我在 file.txt
中:
big bird|Big birds tend to be big.;;They have wings.
big truck|I love trucks!;;Ford makes nice big trucks.
red truck|Red is my favorite color.;;Red is also a name.
这是我的代码,可以与第一个定界符(|)配合使用,并在其后返回ENTIRE响应.
Here's my code which works fine with the first delimiter (|) and returns the ENTIRE response after it.
read -p " " query
response="$(awk -F\| -v r="$query" '$1==r{print $2;exit}' file.txt)"
echo "$query"
例如,
输入:大鸟
输出:大鸟往往大.;;它们有翅膀.
Output: Big birds tend to be big.;;They have wings.
但是我需要让它第二次返回在同一行以双分号( ;;
)分隔的RANDOM响应.
But I need to get it to return a RANDOM response delimited on the same line a second time with double semicolons (;;
).
因此,当输入该输入时,它应随机返回大鸟往往是大鸟".或它们有翅膀".并非两者都在同一时间.
So, when that input is entered, it should randomly return either "Big birds tend to be big." or "They have wings." Not both at the same time.
有什么想法吗?
推荐答案
尝试:
awk -F\| -v r="$query" '$1==r{print $2;exit}' file.txt |
sed 's/;;/\n/g' | shuf -n1
这篇关于BASH-file.txt中的正则表达式匹配行具有多个定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!