sed on OSX – How to Insert at a Certain Line

gnuosxposixsed

So I've been using 'sed' on linux for a while, but have had a bit of difficulty trying to use it on OSX since 'POSIX sed' and 'GNU sed' have so many little differences. Currently I'm struggling with how to insert a line of text after a certain line number. (in this case, line 4)

On linux I would do something like this:

sed --in-place "4 a\  mode '0755'" file.txt

So on OSX I tried this:

sed -i "" "4 a\ mode '0755'" file.txt

However this keeps giving me a 'extra characters after \ at the end of a command' error. Any ideas what's wrong here? Do I have a typo? Or am I not understanding another difference between versions of sed?

Best Answer

Strictly speaking, the POSIX specification for sed requires a newline after a\:

[1addr]a\
text

Write text to standard output as described previously.

This makes writing one-liners a bit of a pain, which is probably the reason for the following GNU extension to the a, i, and c commands:

As a GNU extension, if between the a and the newline there is other than a whitespace-\ sequence, then the text of this line, starting at the first non-whitespace character after the a, is taken as the first line of the text block. (This enables a simplification in scripting a one-line add.) This extension also works with the i and c commands.

Thus, to be portable with your sed syntax, you will need to include a newline after the a\ somehow. The easiest way is to just insert a quoted newline:

$ sed -e 'a\
> text'

(where $ and > are shell prompts). If you find that a pain, bash [1] has the $' ' quoting syntax for inserting C-style escapes, so just use

sed -e 'a\'$'\n''text'

[1] and mksh (r39b+) and some non-bash bourne shells (e.g., /bin/sh in FreeBSD 9+)

Related Question