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...
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 (namedfile.txt~)-0makes the character\0the 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.-preads the file record by record, and after reading each, it runs the code and prints the default variable$_-ejust introduces the code.