Python – Replace multiline string in files

awkperlpythonsedtext processing

I have a number of files I want to update by replacing one multi-line string with another multi-line string. Something along the lines of:

* Some text, 
* something else
* another thing

And I want to replace it with:

* This is completely
* different text

The result would be that after the replacement the file containing the first block of text, will now contain the second string (the rest of the file is unchanged).

Part of the problem is that I have to find the list of files to be updated in the file system. I guess I can use grep for that (though again that's not as easy to do with multiline strings) then pipe it in sed maybe?

Is there an easy way to do this? Sed is an option but it's awkward because I have to add \n etc. Is there a way to say "take the input from this file, match it in those files, then replace it with the content of this other file" ?
I can use python if need be, but I want something quick and simple, so if there is a utility available, I would rather use that than write my own script (which I know how to do).

Best Answer

Substitute "Some...\n...Thing" by the contents of file "new" in one or more input files

perl -i -p0e 's/Some.*?thing\n/`cat new`/se' input.txt ...
  1. -i to change input.txt directly
  2. -p0 slurp input file file and print it in the end
  3. s/regexp/.../s in regexp . is .|\n
  4. s/.../exp/e replace by eval(exp)
  5. new -- a file containing the replacement text (This is completely...different text)
  6. if useful you can expand the original text s/Some text\n...\n...thing\n/...
Related Question