bash 如何在 mac os x (BSD) sed 上转义加号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4453760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:06:09  来源:igfitidea点击:

How to escape plus sign on mac os x (BSD) sed?

regexmacosbashsedgrep

提问by Alec Jacobson

I'm trying to find and replace one or more occurrences of a character using sed on a mac, sed from the BSD General Commands.

我正在尝试使用 sed 在 mac 上查找和替换一个或多个字符,来自 BSD 通用命令的 sed。

I try:

我尝试:

echo "foobar" | sed -e "s/o+//g

expecting to see:

期待看到:

fbar

But instead I see

但我看到

foobar

I can of course just expand the plus manually with:

我当然可以手动扩展加号:

echo "foobar" | sed -e "s/oo*//g"

but what do I have to do to get the plus sign working?

但是我该怎么做才能使加号起作用?

回答by khachik

Using the /gflag, s/o//gis enough to replace all o occurrences.

使用该/g标志s/o//g足以替换所有 o 次出现。

Why +doesn't work as expected:in old, obsolete re +is an ordinary character (as well as |, ?). You should specify -Eflag to sedto make it using modern regular expressions:

为什么+不能按预期工作:在旧的,过时的 re+是一个普通字符(以及|, ?)。您应该使用现代正则表达式指定-E标志以sed使其成为:

echo "foobar" | sed -E -e "s/o+//"
# fbar

Source: man 7 re_format.

资料来源:man 7 re_format

回答by stever

echo "foobar" | sed -e "s/o\+//g"

worked for me on Mac OS X 10.6.

在 Mac OS X 10.6 上对我来说有效。

I remembered that I replaced my BSD version of sed with GNU sed 4.2, so this may or may not work for you.

我记得我用 GNU sed 4.2 替换了我的 BSD 版本的 sed,所以这可能对你有用,也可能不适合。

回答by Marco Carvalho

Sed is sad for regexes. You could either try the -E, which might work with BSD, or you could try this one instead:

Sed 为正则表达式感到难过。你可以试试 -E,它可能适用于 BSD,或者你可以试试这个:

sed -e "s/o\{1,\}/"

Perhaps there are too many sed's out there to have a usable tool on any system.

也许有太多的 sed 在任何系统上都没有可用的工具。

回答by XY WANG

You can use this, on linux or unix.

您可以在 linux 或 unix 上使用它。

echo "foobar" | perl -pe "s/o+//g"