-1

How can I identify specific pattern between two outside delimiters '{' and '}' in text and randomize it inside with delimiter ';'

Examples:

Input: I have {red;green;orange} fruit

Output: I have green fruit

Complicated input: I have {red;green;orange} fruit and cup of {tea;coffee;juice}

Output: I have red fruit and cup of tea

jdoe1989
  • 13
  • 2
  • 3
    Extract the text into a variable. Convert it into an array. Select a random element of the array. Replace the delimited text with the selected element. – Barmar Dec 23 '15 at 22:49
  • 3
    Each of those steps should be relatively straightforward, so please make an attempt. If you can't get it to work, show what you tried and explain the problem you're having. – Barmar Dec 23 '15 at 22:50

3 Answers3

0

For example:

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

produces

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
clt60
  • 62,119
  • 17
  • 107
  • 194
0

Very simple way of randomizing the insides of sentances using the variable RANDOM and modulus.

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."

If using the delimiters inside your sentence is absolutely necessary, it would be a bit more interesting, and involve the need for cut, but use the same random number generator used above. An example might look something like this:

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"

In this case, if $rand generated as 2, you would get the sentence "I have green fruit." Please ask if you have any questions.

Skyler
  • 186
  • 1
  • 6
0

Using [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

Output:

I have green fruit and cup of coffee
I have green fruit and cup of tea

Pretty simple code, should not need explanation.

anishsane
  • 20,270
  • 5
  • 40
  • 73