Say I have a text file text.txt
and I want to replace a (multi-line) string that is contained in before.txt
with another string that is contained in after.txt
, how do I do that? (I dont want to use regular expression I literally want to replace the string contained in before.txt
with the text contained in after.txt
in text.txt
.
I was hoping to use the methods proposed in: https://unix.stackexchange.com/a/26289/288916
I tried:
perl -i -p0e 's/`cat before.txt`/`cat after.txt`/se' text.txt
But unless I am a complete idiot and messed something trivial up I cannot simply extend it to loading a string to be found from a file with cat.
Perhaps something is going wrong with the escaping. The file before.txt
contains symbols such as /[]"
.
Thanks @ilkkachu, I tried:
perl -i -0 -pe '$b = `cat before.txt`; $a = `cat after.txt`; s/\Q$b\E/$a/s\' text.txt
, but it is still not working correctly. I got it working in one instance by making sure the string in before exactly matches the whole lines in which the strings was to be replaced. But it does not work for instance to replace a string that is not found at the start of the line.
Example: text.txt
file containing:
Here is
some text.
before.txt
contains: text
after.txt
contains: whatever
No chance is made.
perl -p
orperl -n
handle the lines of the file one after the other and don't deal with the whole file at once. So you cannot simply replace a multi-line string using this method. – Steffen Ullrich Dec 06 '19 at 17:47