Using Perl regex over multiple lines

I'd like to replace all occurrences of this in a file:

ab
ba

With this:

a a

I tried the obvious:

$ perl -i -p -e 's/ab\nba/a a/' file.txt

With no success. How is this done?

I can't find any questions that properly articulate this question.

1 Answer

Without any other options, -p processes the input line by line. No line can contain anything after the \n. You have to change the record separator:

perl -i~ -0pe 's/ab\nba/a a/' file.txt
  • -i~ will modify the file "in place", leaving a backup behind (named file.txt~)
  • -0 makes the character \0 the input record separator. The important thing is it doesn't occur in the string to be replaced, so it will never read just a part of it.
  • -p reads the file record by record, and after reading each, it runs the code and prints the default variable $_
  • -e just introduces the code.
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like