0

file1 contents:

1111
2222
3333
4444

file2 contents:

[webservers]
[databases]

I want the file2 contents to look like: After adding all the lines, insert a new line.

[webservers]
1111
2222
3333
4444

[databases]

2 Answers 2

0

Use the read command of sed to append a file after a pattern and the substitute command to insert a newline:

sed -e '/\[webservers]/r file1' -e 's/\[databases]/\           
   &/' file2

Note that you need to escape the newline with a backslash as shown above to include it in the substitute pattern (the & stands for the whole match, so the match is replaced by itself, preceeded with a newline).

Also the [ needs to be escaped to suppress its special meaning.

2
  • I am getting a sed: -e expression #2, char 27: unterminated s' command error.` Is there a space before &. Doing this modification and putting the command in one line is fixing it: sed -e '/\[heb_servers]/r file1' -e 's/\[kroger_servers]/\n\n&/' file2 I ultimately want more than one file to be inserted into file2 and the single line command with absolute path is getting very long: sed -e '/\[webservers]/r /home/user/file1' -e 's/\[databases]/\n\n&/' -e '/\[databases]/r /home/user/file3' -e 's/\[local]/\n\n&/' /home/user/Downloads/file2 > /home/user/Downloads/hosts
    – Cruise5
    Commented Aug 24, 2022 at 5:58
  • The second expression doesn't have 27 chars, so something went wrong on copying the command. Anyhow, you seem to have GNU sed, so you can use \n in the replacement as newline (note that this is not portable). This also means you can write everything into one expression: sed -e '/\[webservers]/r /home/user/file1;s/\[databases]/\n\n&/;//r /home/user/file3;s/\[local]/\n\n&/'. I also took advantege of repeating the last regexp by using an empty pattern.
    – Philippos
    Commented Aug 24, 2022 at 8:54
0

GNU sed with extended regex mode.

Sed command "a" can also be used here to append a trailing newline in the files being added.

sed -E \
  -e '/\[webservers]/r file1' \
  -e '/\[databases\]/r file3' \
  -e '/\[webservers]|\[databases]/a\
' \
file2 >hosts

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.