I want to replace the middle of some text with a string from an array.
#!/bin/bash
array=(1 2 3 4 5 6)
for i in "${array[@]}"; do
# doesn't work
echo "some text" | perl -pe 's|(some).*(text)|\1$i\2|'
done
I am using perl regex instead of sed for its easier non-greedy matching support. What's the correct syntax for getting the value of $i in there?
Just replace the single quotes around the regexp with double quotes.
#!/bin/bash
array=(1 2 3 4 5 6)
for i in "${array[@]}"; do
echo "some text" | perl -pe "s|(some).*(text)|\1$i\2|"
done
Single quotes do not expand the variable.
There's a couple of approaches you could take. The problem is, the string you're passing to perl is single quoted, which means it won't be interpolated. That's normally good news, but in this case you're passing through $i
literally, and there's no perl variable with that name.
One approach is to export
it an then read it in via the %ENV
hash:
export VALUE=3;
perl -e 'print $ENV{'VALUE'},"\n";'
Otherwise, you 'just' need to interpolate the string first:
VALUE=3
perl -e "print $VALUE;"
Although in your example - I'd be suggesting don't bother using shell at all, and rewrite:
#!/usr/bin/perl
my @array = qw (1 2 3 4 5 6);
foreach my $element ( @array ) {
my $text = "some text";
$text =~ s|(some).*(text)|$1$element$2|;
print $text,"\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With