5

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?

1
  • Did you try double quotes around the regexp? Single quotes do not expand the variable. Commented May 13, 2015 at 12:23

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The perl part should be: perl -pe "s|(some).*(text)|${1}$i\2|"
4

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";
}

Comments

2

There is a bit dirty trick that actually works in most cases: just end the string in the single quotes, insert the bash variable, and restart the single-quoted string. It's important not to insert any spaces between those three parts, as in the following sample:

#! /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

Note that I had to replace \1 with ${1}, otherwise perl would interpret it as \11, \12, etc.

Comments

0

Actually, there is another problem existing. If you run code below, you won't get expected result.

#!/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

It is caused that after bash variable is expanded, perl code becomes perl -pe "s|(some).*(text)|\11\2|", then you got \11 not \1 so match value is wrong.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.