在Mac上使用sed命令时出现“p命令后有额外字符”的错误提示。

17

在Linux上,我使用以下命令获取 [test] 行之后的两行内容:

sed -n '/\[test\]/{n;p;n;p}' my-file

在 Mac 上我得到:

sed: 1: "/\\[test\\]/{n;p;n;p}": extra characters at the end of p command.

有没有一种表达方式可以在两个平台上都使用,或者在 Mac 上必须使用完全不同的命令?

3个回答

26

另外,如果你在使用 -i 选项但没有扩展名时遇到此错误:

> sed -i 's/foo/bar/g' file
sed: 1: "file": extra characters at the end of p command

在这种情况下,解决方案是将扩展名明确地设置为空字符串:

> sed -i '' 's/foo/bar/g' file

16
在最后一个p后添加一个额外的分号。
 sed -n '/\[test\]/{n;p;n;p;}' my-file

(与Mac版本无关,MSYS上也失败)


5

苹果操作系统(BSD)的sed命令需要每个命令以;结尾或单独成行。

因此,下面的代码可以正常工作:

sed -n '/\[test\]/{n;p;n;p;}' my-file

甚至这个也可以使用:

sed -n '/\[test\]/{
n
p
n
p
}' my-file

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接