sed将扩展正则表达式怎么走吗? - How to get sed to take extended regular expressions?

- 此内容更新于:2015-12-20
主题:

我想做字符串替换使用正则表达式。现在,我意识到,sed是时髦的Mac的行为。我经常看到工作区使用当我想检查一定模式在一条线。但是,在这种情况下我想做字符串替换。我想替换。我试着以下,工作在扩展正则表达式:当然这并没有什么。我试着egrepping,当然它的线条。我怎么才能sed使用扩展正则表达式替换吗?或者是一个更好的方法来使用正则表达式替换吗?我在macosx。

原文:

I want to do string replacement using regular expressions in sed. Now, I'm aware that the behavior of sed is funky on a Mac. I've often seen workarounds using egrep when I want to just examine a certain pattern in a line. But, in this case I want to do string replacement.

I want to replace cp an and cp <tab or newline> an with gggg. I tried the following, which would work under extended regular expressions:

sed -i'_backup' 's/cp\s+an/gggg/g'  

But of course this does nothing. I tried egrepping, and of course it picks out the lines with cp <one or more space characters> an.

How do I get sed to do replacement using extended regular expressions? Or what is a better way to do replacement using regular expressions?

i'm on mac osx.

网友:安装GNUcoreutils会给你访问GNUsed。如果你已经自酿酒。

(原文:Installing GNU coreutils will give you access to GNU sed. brew install coreutils if you have Homebrew already.)

网友:这问可能更适合在相关网站apple.stackexchange.com(AskDifferent)。考虑使用底部的链接你的问,问主持人移动它。祝你好运。

(原文:This Q may be more appropriate on the related site apple.stackexchange.com (AskDifferent). Consider using the flag link at the bottom of your Q and ask the moderator to move it there. Good luck.)

网友:手册页获得解释说在一段名为“Sed正则表达式”。re_format手册页的链接,这就解释了“现代”的特点。“扩展”)正则表达式。

(原文:The man page for sed explains in a section helpfully titled "Sed Regular Expressions". It links to the re_format man page, which explains the features of "modern" (a.k.a. "extended") regular expressions.)

解决方案:
OSX以下命令将扩展正则表达式支持:POSIX字符类引用
原文:

On OSX following command will work for extended regex support:

sed -i.backup -E 's/cp[[:blank:]]+an/gggg/g'

POSIX Character Class Reference

网友:好吧我试试这个。我在哪里寻找诸如文档?

(原文:Okay I'll try this. Where do I find documentation for such things as [[blank]]?)

网友:添加了一个参考答案POSIC字符类。

(原文:Added a reference in answer for POSIC character classes.)

解决方案:
既然你提到你想要处理,你需要哄sed。您的确切需求我不太清楚,但下面的例子说明了sed可以很容易地处理某些情况下一个换行符是“目标”正则表达式:(注意non-Mac读者:如果你的grep不支持,尝试相反)。
原文:

Since you mentioned you want <newline> to be handled, you'll need to coax sed a bit. Your exact requirements aren't too clear to me but the following example illustrates that sed can easily handle certain cases in which a newline is in the "target" regex:

$ echo $'cp\nancp an' | sed -E '/cp/{N; s/cp(\n|[[:blank:]])an/gggg/g;}'
gggggggg

(Note to non-Mac readers: If your grep does not support -E, try -r instead.)