Bry*_*unt 4 osx bsd sed compatibility
这在任何 Linux 上都能很好地工作:
$ echo foo bar | sed -n '/foo/{/bar/{;p;}}'
foo bar
Run Code Online (Sandbox Code Playgroud)
但在 OSX 的古老 BSD 变体上失败:
? echo foo bar | sed -n '/foo/{/bar/{;p;}}'
sed: 1: "/foo/{/bar/{;p;}}": extra characters at the end of } command
Run Code Online (Sandbox Code Playgroud)
我错过了一些神奇的咒语吗?有没有办法以可移植的方式编写它?
我不想不得不恢复到grep | grep | grep
命令管道。
更新:这里的代表很低,所以不能投票,但感谢所有回复者的深思熟虑的建议。
甲sed
编辑命令应该由终止;
或文字换行符。GNUsed
对此非常宽容。
你的脚本:
/foo/{/bar/{;p;}}
Run Code Online (Sandbox Code Playgroud)
扩展:
/foo/{
/bar/{
p
}
}
Run Code Online (Sandbox Code Playgroud)
这将作为sed
馈送到sed
through的脚本工作-f
。
如果我们确保将换行符替换为;
(仅在命令和命令{...}
组的末尾需要)以便我们可以在命令行上使用它,我们会得到
/foo/{/bar/{p;};}
Run Code Online (Sandbox Code Playgroud)
这适用于 OpenBSD sed
(原版没有,因为第二个;
缺失)。
在这种特殊情况下,这可以进一步简化为
/foo/{/bar/p;}
Run Code Online (Sandbox Code Playgroud)