3

I can append to the start of a file fine with:

sed -i '1s/^/word\n/' file

I'm reading that if I use double quotes I can expand variables, so I try:

sed -i "1s/^/$(printenv)\n/" file

I end up getting back:

sed: -e expression #1, char 15: unterminated `s' command

What is happening here. Is it related to the contents of the variable or something else?

  • $(command) is not a variable... – don_crissti Oct 14 '17 at 15:27
7

I think the following would work:

sed -i '1 e printenv' file

From the GNU sed manual:

'e COMMAND'
     Executes COMMAND and sends its output to the output stream.  The
     command can run across multiple lines, all but the last ending with
     a back-slash.

Alternatively, you can use cat, but this requires creating a temporary file:

cat <(printenv) file > temporary_file; mv temporary_file file

If the package moreutils is installed on your machine, you can avoid creating a temporary file manually by using sponge:

cat <(printenv) file | sponge file
5

To insert the contents before line 1:

ed -s file <<< $'0r !printenv\nwq'

To insert the contents after line 1:

ed -s file <<< $'1r !printenv\nwq'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.