我們在編寫bash腳本的時候,經常需要替換掉字符窗中特殊的字符,我們看看有幾種方法可以實現。
- 最常用的方法是使用sed命令。例如
[nhuang@localhost test]$ a="This is a / and you will know /" ; echo "$a" | sed "s/\//\\\\\//g" This is a \/ and you will know \/
但是相當復雜,應為在替換部分要使用雙反斜杠,"\\\\\/",而不是"\\\/",為什么呢?應為在escape"\“的時候,必須要使用"\\",而不是對待"/"的"\/"。例如
[nhuang@localhost test]$ a="This is a / and you will know /" ; echo "$a" | sed -s "s/\//\//g" This is a / and you will know / [nhuang@localhost test]$ a="This is a / and you will know /" ; echo "$a" | sed -s "s/\//\\\\/g" This is a \ and you will know \ [nhuang@localhost test]$ a="This is a / and you will know /" ; echo "$a" | sed -s "s/\//\\/g" sed: -e expression #1, char 8: unterminated `s' command
- 那么,第二種方法是什么呢?使用${}這個符號,例如:
[nhuang@localhost test]$ a="This is a / and you will know /" ; echo ${a//\//\\} This is a \ and you will know \ [nhuang@localhost test]$ a="This is a / and you will know /" ; echo ${a//\//\\\/} This is a \/ and you will know \/
這里,我們不再需要使用"\\"了,而是正常的使用正則表達式。所以,第二種方法,最為方便。如果使用expr substr,則會把問題復雜化。dan
- 但是,如果要同時替換多個不同位置的字符串,例如"/", "\", "?",等,要在他們前面都加上反斜杠,使用sed,用-e,或者"{;}"來操作。
[nhuang@localhost test]$ str="asdasdf / asdfasdf / asdf,adf" ; echo $str | sed "{s/\//\\\\\//g;s/,/:/g}" asdasdf \/ asdfasdf \/ asdf:adf
- 我們也可以使用多次的${}來做替換,例如:
[nhuang@localhost test]$ str="This is / and This is & " ; str=`echo ${str//\//\\\/}` ; str=`echo ${str//&/\\\&}` ; echo $str This is \/ and This is \& [nhuang@localhost test]$ str="This is / and This is \\" ; str=`echo ${str//\//\\\/}` ; str=`echo ${str//\\\/\\\\\\\}` ; echo $str This is \\/ and This is \\ [nhuang@localhost test]$ str="This is / and This is \ " ; str=`echo ${str//\//\\\/}` ; str=`echo ${str//\\\/\\\\\\\}` ; echo $str This is \\/ and This is \\
第二個和第三個有點復雜:(,
資料:
http://www.cnblogs.com/frydsh/p/3261012.html
