Mac OS X上的SED

时间:2012-08-13 16:21:35

标签: macos bash sed gnu bsd

所以我试图通过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

2 个答案:

答案 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

编辑:哦,我错过了你实际上在你的变量中有反斜杠 - 后跟N而不是文字换行符。如果您使用文字换行符,则上述应该有效。

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)

相关问题