所以我试图通过macports安装gsed,但这还没有解决问题。我打算卸载它以减少混乱,但是,在我这样做之前,我将如何修复下面的错误。这是因为BSD版本的sed Mac OS X正在按照我的理解运行,但我似乎没有发现任何修复都有帮助。
sed: 1: "/\[staging: production\ ...": command i expects \ followed by text
#!/bin/bash
test="lala\nkjdsh"
sed -i -e '/\[staging: production\]/ i '$test'' ./test.txt
答案 0 :(得分:1)
由于$test
中的“\ n”,您遇到此问题。尝试从中删除\n
。
POSIX标准sed
仅接受\n
作为搜索模式的一部分。 OS X使用FreeBSD sed
,它严格遵守POSIX
因此,如果您需要在变量中添加换行符,则需要编写类似的内容:
$ test="lala\
> kjdsh"
您还可以使用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"
$ perl -n -i -e 'print "'"$test"'\n" if /\[staging: production\]/; print;' ./test.txt
$ cat ./test.txt
lala
kjdsh
[staging: production]
答案 1 :(得分:1)
如果测试变量不包含仅包含.
的行,则可以使用ed
编辑文件:
printf '%s\n' '/\[staging: production\]/i' "$test" . w | ed -s ./test.txt
有关ed
的更多信息,请参阅http://wiki.bash-hackers.org/howto/edit-ed。
EDIT2:鉴于评论中给出了pastebin,请尝试:
#!/usr/bin/env bash
#...
ed -s ./test.txt << EOF
/\[staging: production\]/i
; some comment
someStuffHere[] = "XYZ"
someMoreStuff[] = "$someShellVar"
; another comment
.
w
EOF
一行上的.
结束i
nsert命令,而w
是写命令,它实际上保存了对文件的更改(如:w
在vim)