分页: 1 / 1

有关转义字符的问题

发表于 : 2014-07-17 9:15
Red_Hair
移除多余空格
使用下面的指令,但书上讲的\+是赋予+特殊的含义,这个就不明白来,\不是转义字符吗?\+应该是是+失去特殊含义才对嗄,不清楚怎么回事,请大N解答
sed 's/[ ]\+/ /g'

Re: 有关转义字符的问题

发表于 : 2014-07-17 11:50
astolia
因为sed的正则默认用的是Basic Regular Expression(BRE) 规则

代码: 全选

man sed
REGULAR EXPRESSIONS
POSIX.2 BREs should be supported, but they aren't completely because of
performance problems. The \n sequence in a regular expression matches
the newline character, and similarly for \a, \t, and other sequences.
而BRE中+和其他一些字符并没有特殊意义,需要加\

代码: 全选

code grep
Basic vs Extended Regular Expressions
In basic regular expressions the meta-characters ?, +, {, |, (, and )
lose their special meaning; instead use the backslashed versions \?,
\+, \{, \|, \(, and \).

Re: 有关转义字符的问题

发表于 : 2014-07-17 11:57
astolia
另外,用-r选项可以让sed使用ERE,+就不需要加\了

代码: 全选

$ echo "a    b" | sed -r 's/[ ]+/ /g'
a b
更多BRE和ERE的故事,可以看这篇
http://blog.csdn.net/xiaotengyi2012/art ... ls/8255005