Sed Command – Insert Lines from One File to Another After Keyword

sedtext processing

I have one file that contains the following:

10.48.29.68 doggy
10.65.8.184 kitty
10.48.15.104 froggy

I need to insert the contents of this file into my hosts file after the line bc group in the hosts file.

The hostfile of the server already has hundreds of entries. Bc is a group here in our hosts file. I want code that reads the ip addresses and hostnames in my file above and put those entries in the hosts file below the heading bc group.

The new file above should be written in the hosts file after keyword bc group.

For example, if my hosts file contains these lines:

10.59.12.232 bc4
10.48.29.68 xy9
bc group
10.63.71.136 bc2
10.63.71.214 bc3

I need to convert the hosts file to this:

10.59.12.232 bc4
10.48.29.68 xy9
bc group
10.48.29.68 doggy
10.65.8.184 kitty
10.48.15.104 froggy
10.63.71.136 bc2
10.63.71.214 bc3

I need to append all of the lines from my first file after the line bc group in my hosts file, and then continue with the remaining lines in the hosts file.

Best Answer

Try this:

sed '/^bc group$/ r file1' hostfile

This sed command copies the lines from hostfile to the output and reads (inserts) the lines of file1 after any (and all) bc group line(s) in hostfile.

To save the output in another file, append > newhostfile to the command:

sed '/^bc group$/ r file1' hostfile > newhostfile

However, I recommend this way, which makes a backup with the suffix .bak, and edits the file in place:

sed -i.bak '/^bc group$/ r file1' hostfile

If the bc group line appears more than once in the hostfile, the lines of file1 will be inserted more than once.

Related Question