Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a BASH variable into a PERL regex replacement?

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?

like image 867
user923487 Avatar asked May 13 '15 12:05

user923487


2 Answers

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.

like image 168
NaN Avatar answered Nov 02 '22 22:11

NaN


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";
}
like image 41
Sobrique Avatar answered Nov 02 '22 22:11

Sobrique