使用" +"在sed正则表达式中

时间:2014-10-10 07:15:18

标签: regex linux

echo "  lfj"|sed -e "s/^\s+//g"
  lfj

我记得+表示one or more,所以lfj前面有两个空格,为什么不能剥离它们?

2 个答案:

答案 0 :(得分:3)

您需要转义+

$ echo "  lfj"|sed -e "s/^\s\+//g"
lfj

Basic sed使用BRE(Basic REgular Expressions)。要使+在BRE中重复前一个字符一次或多次,您需要将其转义。

在sed中启用扩展正则表达式选项-r,使sed使用ERE而不是BRE。

$ echo "  lfj"|sed -r "s/^\s+//g"
lfj

答案 1 :(得分:1)

使用-r

echo "  lfj"|sed -re "s/^\s+//g"

来自http://www.grymoire.com/Unix/Sed.html

A quick comment. The original sed did not support the "+" metacharacter. GNU sed does if 
you use the "-r" command line option, which enables extended regular expressions. The "+" 
means "one or more matches". 

也来自https://www.gnu.org/software/sed/manual/sed.html

-r
--regexp-extended
Use extended regular expressions rather than basic regular expressions. Extended regexps 
are those that egrep accepts; they can be clearer because they usually have less backslashes, 
but are a GNU extension and hence scripts that use them are not portable.