regexperl

Perl - Replace pattern only in lines matching another pattern


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.


Solution

  • 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_/"