Search code examples
perlone-liner

Perl regex match string including multiple newlines


How do I match a multiple line string in a file like

# custom prompt
aa=`command1 arg1 arg2`
bb=`command2 arg3 arg4`
PS1="$aa$bb"
# custom prompt

I am using this

perl -0pe 's/# custom prompt\n.*\n.*\n.*\n# custom prompt\n//gm' -i .bashrc

I want to delete all the lines between # custom prompt ~ # custom prompt (including the # custom prompt lines). But the one liner works only for 5 lines cases. Is there a way to match arbitrary multiple lines with new lines like (this does not work)

perl -0pe 's/# custom prompt[\n.]+# custom prompt\n//gm' -i .bashrc

Solution

  • Removing lines:

    perl -i -0pe 's/# custom prompt.*?# custom prompt\s*\n//s' .bashrc
    

    or with anchors

    perl -i -0pe 's/^# custom prompt.*^# custom prompt\n//sm' .bashrc
    #                                                      ^
    #                                               needed m modifier
    

    .*? is the no-greedy way to write .*.