*Bash:字符串替换。

我们在编写bash脚本的时候,经常需要替换掉字符窗中特殊的字符,我们看看有几种方法可以实现。

  1. 最常用的方法是使用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

     

  2. 那么,第二种方法是什么呢?使用${}这个符号,例如:
    [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

  3. 但是,如果要同时替换多个不同位置的字符串,例如"/", "\", "?",等,要在他们前面都加上反斜杠,使用sed,用-e,或者"{;}"来操作。
    [nhuang@localhost test]$ str="asdasdf / asdfasdf / asdf,adf" ; echo $str | sed "{s/\//\\\\\//g;s/,/:/g}" 
    asdasdf \/ asdfasdf \/ asdf:adf

     

  4. 我们也可以使用多次的${}来做替换,例如:
    [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

转载于:https://www.cnblogs.com/nhuang2/p/5767840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值