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 aftera\
:This makes writing one-liners a bit of a pain, which is probably the reason for the following GNU extension to the
a
,i
, andc
commands:Thus, to be portable with your
sed
syntax, you will need to include a newline after thea\
somehow. The easiest way is to just insert a quoted newline:(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[1] and mksh (r39b+) and some non-bash bourne shells (e.g., /bin/sh in FreeBSD 9+)