如何在文本中识别两个外部分隔符“ {”和“} ”之间的特定模式,并使用分隔符“;
示例:
输入: 我有{红色;绿色;橙色}水果
输出: 我有绿色水果
复杂的输入: 我有{红色;绿色;橙色}水果和一杯{茶;咖啡;果汁}
输出: 我有红色水果和一杯茶
答案 0 :(得分:0)
例如:
for i in {1..10}
do
perl -plE 's!\{(.*?)\}!@x=split/;/,$1;$x[rand@x]!ge' <<<'I have {red;green;orange} fruit and cup of {tea;coffee;juice}'
done
产生
I have red fruit and cup of coffee
I have red fruit and cup of juice
I have red fruit and cup of juice
I have orange fruit and cup of juice
I have orange fruit and cup of tea
I have red fruit and cup of coffee
I have orange fruit and cup of tea
I have green fruit and cup of tea
I have red fruit and cup of juice
I have green fruit and cup of juice
答案 1 :(得分:0)
使用变量RANDOM和模数随机化变量内部的非常简单的方法。
rand=$(((RANDOM % 3) + 1))
if [ $rand = 1 ];then
color="red"
elif [ $rand = 2 ];then
color="orange"
elif [ $rand = 3 ];then
color="green"
fi
echo "I have $color fruit."
如果在句子中使用分隔符是绝对必要的,那么它会更有趣,并且需要剪切,但使用上面使用的相同随机数生成器。示例可能如下所示:
sent="I have {red;green;orange} fruit"
rand=$(((RANDOM % 3) + 1))
pref="$(echo $sent | cut -f1 -d"{")"
mid="$(echo $sent | cut -f2 -d"{" | cut -f1 -d"}" | cut -f$rand -d";")"
suff="$(echo $sent | cut -f2 -d"}")"
echo "$pref$mid$suff"
在这种情况下,如果$ rand生成为2,你会得到句子&#34;我有绿色水果。&#34;如果您有任何问题,请询问。
答案 2 :(得分:0)
使用[g]awk
:
$ a='I have {red;green;orange} fruit and cup of {tea;coffee;juice}'
$ awk -F '[{}]' '
BEGIN{ srand() }
{
for(i=1;i<=NF;i++){
if(i%2)
printf "%s", $i;
else {
n=split($i,a,";");
printf "%s", a[int(rand() * n) + 1];
}
print "";
}' <<< $a
输出:
I have green fruit and cup of coffee
I have green fruit and cup of tea
非常简单的代码,不需要解释。