I want to replace a line in a file with multiple lines. I know I can use \n
in the sed
replace, but that is rather ugly. I was hoping to HEARDOCs.
So I can do this to replace the line with multiple lines:
$ cat sedtest
DINGO=bingo
$ sed -i -e "s/^DINGO.*$/# added by $(whoami) on $(date)\nDINGO=howdy/" sedtest
$ cat sedtest
# added by user on Sun Feb 3 08:55:44 EST 2019
DINGO=howdy
In the command I want to put the replacement in new lines so it's easier to read/understand. So far I have been using HEREDOCs when I want to add new lines to a file:
CAT << EOF | sudo tee -a file1 file2 file3
line one
line two
line three
EOF
And this has worked well for appending/adding. Is it possible to do something similar but instead use the output as the replacement in sed
or is there some other way to do what I'm looking for?
This might work for you (GNU sed):
This replaces lines starting
DINGO
with the here-document which is piped to stdin as file within the sed command.An alternative:
N.B. In the alternative solution the here-doc will only be read once!
Is this what you're trying to do?
Note that the above is using literal string operations so it'll work for any characters in the old or new strings unlike your sed script which would fail given
/
s or any ERE regexp character or capture groups or backreferences or... in the input (see Is it possible to escape regex metacharacters reliably with sed for details).