今天被这个方括号懵晕了,特此记录
例如: 去除输入字符串“1[2.3]4[ab,c]”中的所有方括号和逗号:
$ echo "1[2.3]4[ab,c]"|sed -e "s/[,\]\[]//g"
1[2.3]4[ab,c]
It doesn't work!
原因:Regular Expressions
The <right-square-bracket> ( ']' ) shall lose its special meaning and represent itself in a bracket expression if it occurs first in the list (after an initial <circumflex> ( '^' ), if any).
解决方案:关键是要把 ] 右方括号不加escape放在首位.
$ echo "1[2.3]4[ab,c]"|sed -e "s/[][,]//g"
12.34abc
$ echo "1[2.3]4[ab,c]"|sed -e "s/[]\[,]//g"
12.34abc
$ echo "1[2.3]4[ab,c]"|sed -e "s/[],[]//g"
12.34abc
The order of some characters is important:
-should be at the end like this-][]should be like that[][other characters]'should be escaped like that'\''- not begin with
^like in[^ - not begin with
[.[=[:and end with.]=]:] - not end with
$]
References:
regex - How to escape square closing bracket in sed - Stack Overflow
Regular Expressions