2

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 1

4

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
  • Finally, what I was looking for - to add apply plugin to the top of all my build.gradle files. I thought /s would work but s{^}{apply plugin}s replaces the beginning of every line and I don't understand why. Commented Apr 29, 2021 at 16:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .