如何让sed采用扩展的正则表达式?

时间:2021-11-16 20:27:30

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.

我想在sed中使用正则表达式进行字符串替换。现在,我知道sed的行为在Mac上很时髦。当我想要检查一行中的某个模式时,我经常看到使用egrep的变通方法。但是,在这种情况下,我想做字符串替换。

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:

我想用gggg替换cp an和cp an。我尝试了以下内容,它可以在扩展的正则表达式下工作: 或newline>

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.

但当然这没有任何作用。我尝试了egrepping,当然它选择了cp <一个或多个空格字符> a的行。

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.

我在mac osx上。

2 个解决方案

#1


1  

On OSX following command will work for extended regex support:

在OSX下面的命令将适用于扩展的正则表达式支持:

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

POSIX Character Class Reference

POSIX字符类参考

#2


1  

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:

既然你提到要处理 ,你需要稍微哄一下sed。你的确切要求对我来说不是很清楚,但下面的例子说明sed可以轻松处理新行在“目标”正则表达式中的某些情况:

$ 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.)

(非Mac阅读器注意:如果你的grep不支持-E,请尝试使用-r。)

#1


1  

On OSX following command will work for extended regex support:

在OSX下面的命令将适用于扩展的正则表达式支持:

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

POSIX Character Class Reference

POSIX字符类参考

#2


1  

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:

既然你提到要处理 ,你需要稍微哄一下sed。你的确切要求对我来说不是很清楚,但下面的例子说明sed可以轻松处理新行在“目标”正则表达式中的某些情况:

$ 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.)

(非Mac阅读器注意:如果你的grep不支持-E,请尝试使用-r。)