sed command to replace a string from one file with entire contents of another file

I want to write a sed (or awk) command to replace a string from one file with the entire contents of another file. Note that second file from which I want to get the content has more than one line. I tried this:

sed -e "s/PLACEHOLDER/$(sed 's:/:\/:g' TestOutput.txt)/" SQLInput.txt

but got an error saying sed: -e expression #1, char 22: unterminated 's' command

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

try

sed -i '/PLACEHOLDER/ r TestOutput.txt' SQLInput.txt

where

  • -i edit in place
  • /PLACEHOLDER/ search for pattern
  • r TestOutput.txt read file

note that /PLACEHOLDER/ is not deleted.

to have it deleted

sed -i -e '/PLACEHOLDER/ r TestOutput.txt' -e s/PLACEHOLDER// SQLInput.txt

where

  • -e /PLACEHOLDER/d will delete entire line with PLACEHOLDER
  • -e s/PLACEHOLDER// will delete PLACEHOLDER string

Method 2

A sed code is simpler in this case, but since there’s also an awk tag on this question:

awk 'function readfile (file) { getline var < file ; return var }
     BEGIN { RS="^$" }; gsub(/PLACEHOLDER/,readfile("TestOutput.txt"))
' SQLInput.txt


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x