有关转义字符的问题

sh/bash/dash/ksh/zsh等Shell脚本
回复
Red_Hair
帖子: 12
注册时间: 2014-07-04 22:01
系统: ubuntu

有关转义字符的问题

#1

帖子 Red_Hair » 2014-07-17 9:15

移除多余空格
使用下面的指令,但书上讲的\+是赋予+特殊的含义,这个就不明白来,\不是转义字符吗?\+应该是是+失去特殊含义才对嗄,不清楚怎么回事,请大N解答
sed 's/[ ]\+/ /g'
头像
astolia
论坛版主
帖子: 6703
注册时间: 2008-09-18 13:11

Re: 有关转义字符的问题

#2

帖子 astolia » 2014-07-17 11:50

因为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 \).
头像
astolia
论坛版主
帖子: 6703
注册时间: 2008-09-18 13:11

Re: 有关转义字符的问题

#3

帖子 astolia » 2014-07-17 11:57

另外,用-r选项可以让sed使用ERE,+就不需要加\了

代码: 全选

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