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]
Use the r
ead command of sed
to append a file after a pattern and the s
ubstitute 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.
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
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.
Commented
Aug 24, 2022 at 8:54
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