Replace string with contents of a file using sed

I have two different files:

File1

/home/user1/  
/home/user2/bin  
/home/user1/a/b/c

File2

<TEXT1>
<TEXT2>

I want to replace the <TEXT1> of File2 with the contents of File1 using sed. I tried this command, but not getting proper output:

cat File2|sed "s/<TEXT1>/$(cat File1|sed 's///\//g'|sed 's/$/\n/g'|tr -d "n")/g"

You can use other tools also to solve this problem.

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

Here’s a sed script solution (easier on the eyes than trying to get it into one line on the command line):

/<TEXT1>/ {
  r File1
  d
}

Running it:

$ sed -f script.sed File2
/home/user1/
/home/user2/bin
/home/user1/a/b/c
<TEXT2>

Method 2

Took me a long time to find this solution using var replacement. All sed solutions did not work for me, as they either delete complete lines or replace incorrectly.

FILE2=$(<file2)
FILE1=$(<file1)
echo "${FILE2//TEXT1/$FILE1}"

Replaces all occurences of TEXT1 in file2 against content of file1. All other text remains untouched.

Method 3

I answer because the diff/patch method might be of interest in some cases.
To define a substitution of lines contained in file blob1 by lines contained in blob2 use:

diff -u blob1 blob2 > patch-file

For example, if blob1 contains:

hello
you

and blob2 contains:

be
welcome
here

the generated patch-file will be:

--- blob1   2011-09-08 16:42:24.000000000 +0200
+++ blob2   2011-09-08 16:50:48.000000000 +0200
@@ -1,2 +1,3 @@
-hello
-you
+be
+welcome
+here

Now, you can apply this patch to any other file:

patch somefile patch-file

It will replace hello,you lines by be,welcome,here lines in somefile.


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