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

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



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.


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


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


(原文: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.)


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]]?)


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


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;}'

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