考虑以下打字稿:
$ freebsd-version
10.0-RELEASE-p5
$ echo ' found' | sed -n '/[[:blank:]]\+/p'
$ echo ' found' | grep '[[:blank:]]\+'
found
当我在带有 GNU 的 Arch Linux 上执行此操作时sed
:
$ echo ' found' | sed -n '/[[:blank:]]\+/p'
found
$ echo ' found' | grep '[[:blank:]]\+'
found
我做错了吗?为什么它不能在 FreeBSD 上运行?如何让它发挥作用?
答案1
使用 BSD sed,您必须使用选项打开 ERE E
。
echo ' found' | sed -nE '/[[:blank:]]+/p'
答案2
太长了;博士看FD0的解决方案
在询问之前我确实查看了手册页,但没有注意到相关信息,因为我认为它与 Linux 没有太大区别。但,
$ man sed
...
-E Interpret regular expressions as extended (modern) regular
expressions rather than basic regular expressions (BRE's). The
re_format(7) manual page fully describes both formats.
$ man re_format
...
Obsolete (“basic”) regular expressions differ in several respects. ‘|’
is an ordinary character and there is no equivalent for its functional‐
ity. ‘+’ and ‘?’ are ordinary characters, and their functionality can be
expressed using bounds (‘{1,}’ or ‘{0,1}’ respectively). Also note that
‘x+’ in modern REs is equivalent to ‘xx*’. The delimiters for bounds are
‘\{’ and ‘\}’, with ‘{’ and ‘}’ by themselves ordinary characters.
我确实尝试使用{1,}
,但我只是忘记转义大括号。所以肯定FD0的解决方案通常是最好的方法。但其他人会是:
$ echo ' found' | sed -n '/[[:blank:]]\{1,\}/p'
found
$ echo ' found' | sed -n '/[[:blank:]][[:blank:]]*/p'
found
然而,不确定他们的意思
另请注意,现代 RE 中的“x+”相当于“xx*”
意思是,非现代的情况是什么样的。
另外,grep
的联机帮助页没有提到re_format
条目,这显然意味着它有自己的正则表达式实现。就此而言,它是 GNU grep
,而不是sed
.