Using sed to insert file contents

I am trying to insert the contents of a file before the given template

Here is my code:

sed -i "" "/pattern/ { i\\ r $scriptPath/adapters/default/permissions.xml" }" "$manifestFile" 

It adds a path instead of the contents of the file.

Any ideas?

+9
source share
5 answers

To insert text before a template, before reading into a file you need to change the template space in the hold space. For example:

 sed "/pattern/ { h r $scriptPath/adapters/default/permissions.xml g N }" "$manifestFile" 
+20
source

Just delete i\\ .

Example:

 $ cat 1.txt abc pattern def $ echo hello > 2.txt $ sed -i '/pattern/r 2.txt' 1.txt $ cat 1.txt abc pattern hello def 
+4
source

I got something like awk. It looks ugly, but did the trick in its test:

Team:

 cat test.txt | awk ' /pattern/ { line = $0; while ((getline < "insert.txt") > 0) {print}; print line; next } {print}' 

test.txt:

 $ cat test.txt some stuff pattern some other stuff 

insert.txt:

 $ cat insert.txt this is inserted file this is inserted file 

exit:

 some stuff this is inserted file this is inserted file pattern some other stuff 
+1
source

CodeGnome solution does not work if the template is on the last line. Therefore, I used 3 teams.

 sed -i '/pattern/ i\ INSERTION_MARKER ' $manifestFile sed -i '/INSERTION_MARKER/r $scriptPath/adapters/default/permissions.xml' $manifestFile sed -i 's/INSERTION_MARKER//' $manifestFile 
0
source

I tried to answer Todd and it works great,

but I found that the "h" and "g" commands are not allowed.

Thanks to this frequently asked question (found from @vscharf's comments ), Todd's answer might be this liner.

 sed -i -e "/pattern/ {r $file" -e 'N}' $manifestFile 

Edit: If you need a version here, please check this out .

0
source

All Articles