Using sed to insert file content

I tried Todd's answer and it works great,

but I found "h" & "g" commands are ommitable.

Thanks to this faq (found from @vscharf's comments), Todd's answer can be this one liner.

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

Edit: If you need here-doc version, please check this.


Just remove 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

I got something like this using awk. Looks ugly but did the trick in my test:

command:

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

output:

some stuff
this is inserted file
this is inserted file
pattern
some other stuff

In order to insert text before a pattern, you need to swap the pattern space into the hold space before reading in the file. For example:

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

Tags:

Bash

Sed