Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl search and append

Tags:

regex

perl

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?

like image 911
user7086558 Avatar asked Dec 13 '25 07:12

user7086558


1 Answers

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).

like image 98
toolic Avatar answered Dec 16 '25 14:12

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!