Take the 2-minute tour ×

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


sed -i -e '/\[staging: production\]/ i '$test'' ./test.txt
share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

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


$ echo '[staging: production]' > /tmp/test.txt
$ test="lala\nkjdsh"
$ cat ./test.txt
[staging: production]
share|improve this answer
I need to preserve the new lines from the variable and add them to the script –  gazzwi86 Aug 13 '12 at 16:36
I've just described the steps that you need to do when you want to add a newline with sed. Please check it. –  Igor Chubin Aug 13 '12 at 16:40
$test is unquoted so it will be wordsplit after expansion, breaking the perl script into multiple arguments if it contains whitespace. –  geirha Aug 13 '12 at 16:48
@geirha: you are not right, you can check it yourself, or just see my example (I've just added it). But if you suppose that there will be spaces in test you can add doublequotes around it. –  Igor Chubin Aug 13 '12 at 16:53
@IgorChubin try with test='foo bar\n"baz"' –  geirha Aug 13 '12 at 16:55
show 7 more comments

If the test variable does not contain a line containing only . you can use ed to edit the file:

printf '%s\n' '/\[staging: production\]/i' "$test" . w | ed -s ./test.txt

See http://wiki.bash-hackers.org/howto/edit-ed for more about ed.

EDIT: Oh and I missed that you actually had backslash-followed-by-N and not literal newlines in your variable. If you use literal newlines the above should work.

EDIT2: Given the pastebin given in the comments, try:

#!/usr/bin/env bash
ed -s ./test.txt << EOF
/\[staging: production\]/i

; some comment
someStuffHere[] = "XYZ"
someMoreStuff[] = "$someShellVar"

; another comment

The . alone on a line ends the insert command, and w is the write command, which actually saves the changes to the file, (like :w in vim)

share|improve this answer
add comment

Your Answer


