Home > Software engineering >  Sed command not replacing with multiline from file
Sed command not replacing with multiline from file

Time:02-19

I'm trying to replace a bloc in a file (file1) from another one coming from a second file (file2). File2 contains multiline, let's say:

Print 1
Print 2

I'm using this command:

file2="$(cat file2)"
sed -i "/Do_something/,/^}/c\
 echo ${file2} " ${file1}

The good thing is that it works but it replaces it in a single line. How can I replace with multiline? I tried to put directly the variable but It doesn't work, it works only with 'echo'. Also if I add double quotes, it's doesn"t work.

CodePudding user response:

You don't need to read file2 in a shell variable. Just get it done in sed using r file command:

sed -e '/Do_something/,/^}/{/^}/!d; r file2' -e 'd;}' "$file1"

CodePudding user response:

This might work for you (GNU sed):

sed -e '/Do_something/{:a;N;/^}/M!ba;r file2' -e 'd}' file1

Replace the lines between one containing Do_something and another beginning } with the contents of file2.

N.B. The replacement will only take place if both matches are made, otherwise the default action will be leave the file untouched i.e. the N command will reach end-of-file and print the contents of the pattern space.

CodePudding user response:

Using any awk in any shell on every Unix box you could do (untested since you didn't provide sample input/output we could test with):

awk '
    NR==FNR { new = (NR>1 ? new ORS : "") $0; next }
    /Do_something/ { f=1 }
    f && /^}/ { $0=new; f=0 }
    !f
' file2 file1

That above assumes that if you have Do_something in the input then you will also have a subsequent } since nothing in your question suggests otherwise.

If you want to replace the contents of file1 with the output of that command then just add > tmp && mv tmp file1 to the end of the command.

  • Related