且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sed 表达式不允许可选的分组字符串

更新时间:2023-11-04 22:17:10

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.