user7086558 user7086558 - 1 month ago 6
Perl Question

perl search and append

I am trying to write a perl one-liner to search for a string q(abc* and append to it when that string is found. My input file has a bunch of things like this:

q(abc0x[...
q(abc1x[...
q(abc2x[...
q(abc0y[...


I would like the output to be:

q(abc0x_str[...
q(abc1x_str[...
q(abc2x_str[...
q(abc0y_str[...


I've tried this:

perl -pi -e "s/(q\((abc\S+)\[)/\$1_str\1/" file


but the $1 backreference seems to pick up the value from my environment when I type "echo $1" and pre-pends "_str" instead of appending it, giving this output:

-project_strq(abc0x[...


where $1 just happens to be "-project" in my environment.

Alternatively, I've tried:
perl -pi -e "s/(q\(abc\S+)\[)/_str\1/" file


but the output here looks like this instead with the pre-pended _str:

_strq(abc0x[...


Neither output is what I expect. Any advice?

Answer

This produces your desired output:

perl -pi -e 's/(q\(abc\S+)\[/$1_str[/' file

As you noticed, the shell interprets $1 as a shell variable. You need to use single quotes to prevent the shell from treating it as a variable.

The one-liner you originally posted generates an error for me (I see you have now edited your original code).