Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Replace pattern only in lines matching another pattern

Tags:

regex

perl

I'm doing an in-place search & replace with Perl. I need to replace all words in all lines that contain another word. For instance, remove all const only in lines containing PMPI_. With sed I can do:

sed -i "/PMPI_/ s/const//g" file.c

However I need multi-line capabilities and sed doesn't seem to be the right tool for the job. I'm using Perl for everything else anyway. I tried

perl -pi -e "/PMPI_/ s/const//g" file.c

And other variations with no success. I could only find vim regex equivalents searching this site.

like image 217
Alex Avatar asked Sep 03 '25 03:09

Alex


1 Answers

The syntax is:

perl -pi -e "s/const//g if /PMPI_/" file

You can also use a logical AND as in many languages derived from C:

perl -pi -e "/PMPI_/ && s/const//g" file

The second part of the condition s/const//g is evaluated only if the first part /PMPI_/ is true. But even if it is possible to do that, it is a shame in this case to do without the syntax close to natural language that Perl offers.

Note: you say you need multiline capabilities. I don't think you are looking for the slurp mode (that loads the whole file), but you could also work by paragraphs with the -00 option:

echo 'PMPI_ const
const const' | perl -00 -p -e "s/const//g if /PMPI_/"
like image 171
Casimir et Hippolyte Avatar answered Sep 06 '25 13:09

Casimir et Hippolyte