首页 > 解决方案 > 在 mac OS 中将包含特定字符的文件中的字符串替换为“sed”

问题描述

我试图替换文件中包含的任何(0)字符串other。例如,如果文件有以下几行:

apple(0)
apple(20)
orange(70)
banana(0)

在 Linux 中,我可以通过 sed 来完成's/\S*\((0)\)\S*/other/g' file。然后,该文件将被修改为以下内容:

other
apple(20)
orange(70)
other

我也想在 Mac OS X 中做同样的事情,但它不起作用。mac OS 中这种情况的变体是什么?谢谢你。

标签: macossed

解决方案


The regex \S is a GNU extension and can be substituted by [^[:blank:]] in a posix-compliant manner.

Would you please try:

sed 's/[^[:blank:]]*(0)[^[:blank:]]*/other/g' file

(Note that the outer parens to generate capture group is meaningless (harmless) and removed.)

Contents of file:

apple(0)
apple(20)
orange(70)
banana(0)
ABC apple(0)

Output of the sed command above:

other
apple(20)
orange(70)
other
ABC other

I have verified the sed command with the --posix switch.
Hope this helps.


推荐阅读