Search code examples
macosbashsedgnubsd

SED on Mac OS X


So I have tried to install gsed via macports but this hasnt solved the issue. I was going to uninstall it to reduce clutter, however, before I do so, how would i fix the error below. It is because of the BSD version of sed Mac OS X is running from what I understand, but none of the fixes I seem to have found are helping.

sed: 1: "/\[staging: production\ ...": command i expects \ followed by text

#!/bin/bash

test="lala\nkjdsh"
sed -i -e '/\[staging: production\]/ i '$test'' ./test.txt

Solution

  • You have this problem because of "\n" in the $test. Try to remove \n from it.

    POSIX standard sed only accepts \n as part of a search pattern. OS X uses the FreeBSD sed, which is strictly POSIX compliant

    So if you need a newline in a variable you need to write something like:

    $ test="lala\
    > kjdsh"
    

    You can also solve the task with perl:

    $ test="lala\nkjdsh"
    $ perl -n -i -e 'print "'"$test"'\n" if /\[staging: production\]/; print;' ./test.txt
    

    Example:

    $ echo '[staging: production]' > /tmp/test.txt
    $ test="lala\nkjdsh"
    $ perl -n -i -e 'print "'"$test"'\n" if /\[staging: production\]/; print;' ./test.txt
    $ cat ./test.txt
    lala
    kjdsh
    [staging: production]