Search code examples
regexsedtextedit

Replace string between two words with the content of another text file


I am bit new to sed and regex.

I was trying to edit a text file, where I want to replace the contents between two keywords in the first file with the entire contents of another text file

it should like this -

keyword1 inbetweenstuff keyword2

to this

keyword1 textfromfile2 keyword2

I was trying this command, but no luck

sed -i 's/(keyword1).*(keyword2)/\1 contentsoffile2 \2/g' file1.txt

Solution

  • You're trying to use the wrong tool. sed is for simple substitutions on individual lines (s/old/new/), that is all. For anything more interesting you should be using awk.

    With GNU awk for multi-char RS, gensub(), and the 3rd arg for match():

    $ cat file1
    keyword1 IN BETWEEN
    STUFF ON
    ONE OR MORE
    LINES keyword2
    
    $ cat file2
    NOW IS
    THE WINTER OF
    OUR DISCONTENT
    
    $ cat tst.awk
    BEGIN { RS="^$"; ORS="" }
    NR==FNR { new = gensub(/\n$/,"",""); next }
    match($0,/(.*keyword1 ).*( keyword2.*)/,a) { print a[1] new a[2] }
    
    $ awk -f tst.awk file2 file1
    keyword1 NOW IS
    THE WINTER OF
    OUR DISCONTENT keyword2
    

    Note that the above treats the contents of file2 as a literal string so the contents of "file2" can be anything. Try any of the sed solutions if "file2" contains an &, for example (or \1 or / or ...). It also doesn't care how many lines are in file2 or how many lines are between the keywords in file1.