Home > database >  Extract a word between brackets and replace it in a sentence
Extract a word between brackets and replace it in a sentence

Time:12-25

so let's say i have this sentence

It's {raining|snowing|cold} outside

What I want is to randomly extract a word between the brackets, which i did with awk -vRS="}" -vFS="|" '{print $2}' (still working to extract them randomly). The output usually is the second word, in our case snowing.

Thing is that the output is only snowing, and the actual output i want is something like It's snowing outside, so how do I extract any word from the brackets and replace with only one word.

CodePudding user response:

Since you need to rewrite a string by replacing a part of it a regex is one suitable way

use warnings;
use strict;
use feature 'say';

sub pick_one { 
    my ($pattern) = @_; 
    my @choices = split /\|/, $pattern; 
    return $choices[int rand @choices]; 
}

my $sentence = q(It's {raining|snowing|cold} outside); 
    

$sentence =~ s/\{ ( [^}]  ) \}/pick_one($1)/ex; 

say $sentence; 

That /e modifier makes it evaluate the replacement side as code, and the produced value is used as the replacement. So there we run a sub in which the choosing happens. This is also a good way for later refinements/changes, implemented by editing the sub.

An element of the array @choices is selected using rand. An expression for its upper bound is evaluated in the scalar context so we can directly use the @choices array since then its length ends up being used.

CodePudding user response:

With jq it is a one-liner:

echo "It's {raining|snowing|cold} outside" | \
jq -rR --argjson rand $RANDOM 'gsub("{(?<words>[^}] )}"; .words | split("|") | .[$rand % length])'

CodePudding user response:

echo "It's {raining|snowing|cold} outside" | perl -ple 's/\{(.*)\}/(split "[|]", $1)[rand(3)]/e'

or for arbitrary number of weather conditions:

echo "It's {raining|snowing|cold} outside" | perl -ple 's/\{(.*)\}/@a=split "[|]", $1; $a[rand(@a)]/e'
  • Related