Jānis Elmeris
Jānis Elmeris

Reputation: 2045

How to insert the whole matched text in the replacement in Perl?

I want to add a string (A) after all specific other strings (bbc). So, I match bbc and want to replace it with itself with A appended ('aabbcc' => 'aabbcAc').

Is there a replacement back-reference that gets substituted with the whole match?

$0 doesn't seem to work – its content is always "-e", for some reason: $ echo 'aabbcc' | perl -p -e 's/bbc/$0A/g' aa-eAc

Upvotes: 2

Views: 398

Answers (1)

Toto
Toto

Reputation: 91385

Use $&, see https://perldoc.perl.org/perlvar#$&

$ echo 'aabbcc' | perl -p -e 's/bbc/$&A/g'
aabbcAc

Upvotes: 5

Related Questions