sed 表达式不允许可选的分组字符串 [英] Sed expression doesn't allow optional grouped string
问题描述
我正在尝试在 sed
脚本中使用以下正则表达式,但它不起作用:
I'm trying to use the following regex in a sed
script but it doesn't work:
sed -n '/\(www\.\)\?teste/p'
上面的正则表达式似乎不起作用.sed
似乎没有将 ?
应用于分组的 www\.
.
The regex above doesn't seem to work. sed
doesn't seem to apply the ?
to the grouped www\.
.
如果您使用 -E
参数将 sed
切换为使用扩展正则表达式,则它有效,因此语法变为:
It works if you use the -E
parameter that switches sed
to use the Extended Regex, so the syntax becomes:
sed -En '/(www\.)?teste/p'
这工作正常,但我想在不支持 -E
运算符的机器上运行此脚本.我很确定这是可能的,而且我正在做一些非常愚蠢的事情.
This works fine but I want to run this script on a machine that doesn't support the -E
operator. I'm pretty sure that this is possible and I'm doing something very stupid.
推荐答案
Standard sed
只理解 POSIX 基本正则表达式 (BRE),而不是扩展正则表达式 (ERE),?
是 ERE 中的元字符,但不是 BRE 中的元字符.
Standard sed
only understands POSIX Basic Regular Expressions (BRE), not Extended Regular Expressions (ERE), and the ?
is a metacharacter in EREs, but not in BREs.
如果您打开 ERE,您的 sed
版本可能支持 ERE.对于 GNU sed
,相关选项为 -r
和 --regexp-extended
,描述为在脚本中使用扩展的正则表达式".
Your version of sed
might support EREs if you turn them on. With GNU sed
, the relevant options are -r
and --regexp-extended
, described as "use extended regular expressions in the script".
然而,如果您的 sed
不支持它 - 很有道理 - 那么你就被卡住了.要么导入支持它们的 sed
版本,要么重新设计您的处理.也许你应该使用 awk
代替.
However, if your sed
does not support it - quite plausible - then you are stuck. Either import a version of sed
that does support them, or redesign your processing. Maybe you should use awk
instead.
我不知道为什么我没有提到即使 sed
不支持速记 ?
或 \?
符号,它确实支持 \{n,m\}
的计数范围,因此您可以使用 \{0,1\}
模拟 ?
:
I don't know why I didn't mention that even though sed
does not support the shorthand ?
or \?
notation, it does support counted ranges with \{n,m\}
, so you can simulate ?
with \{0,1\}
:
sed -n '/\(www\.\)\{0,1\}teste/p' << EOF
http://www.tested.com/
http://tested.com/
http://www.teased.com/
EOF
产生:
http://www.tested.com/
http://tested.com/
使用标准 BSD sed
和 GNU sed
4.2.2 在 Mac OS X 10.9.1 Mavericks 上测试.
Tested on Mac OS X 10.9.1 Mavericks with the standard BSD sed
and with GNU sed
4.2.2.
这篇关于sed 表达式不允许可选的分组字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!