Bash:随机化分隔符之间的文本

Bash: Randomize text between delimiters

如何识别文本中两个外部定界符“{”和“}”之间的特定模式,并在内部使用定界符将其随机化';'

示例:

输入: 我有{red;green;orange}水果

输出: 我有青果

复杂输入: 我有{red;green;orange}水果和一杯{tea;coffee;juice}

输出: 我有红色水果和一杯茶

例如:

for i in {1..10}
do
    perl -plE 's!\{(.*?)\}!@x=split/;/,;$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

使用变量 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."

如果在你的句子中使用分隔符是绝对必要的,那会更有趣一点,并且涉及到 cut 的需要,但是使用与上面相同的随机数生成器。示例可能如下所示:

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,你会得到这句话 "I have green fruit." Please ask if you have any questions

使用[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

非常简单的代码,应该不需要解释。