sed中使用變量,普通的處理方式無法解析變量
如當前file文件中存在字符串pedis,現將其替換為redis
[root@localhost work]# cat file pedis
如下兩種替換方式,都是行不通的
#!/bin/bash old_str=pedis new_str=redis sed -i 's/$old_str/$new_str/g' file sed -i 's#$old_str#$new_str#g' file
將變量用三個單引號引起來,可以解決上述問題
#!/bin/bash old_str=pedis new_str=redis #sed -i 's/$old_str/$new_str/g' file #sed -i 's#$old_str#$new_str#g' file sed -i 's/'''$old_str'''/'''$new_str'''/g' file
執行結果
[root@localhost work]# cat file pedis [root@localhost work]# ./replace.sh [root@localhost work]# cat file redis
當變量中存在特殊字符/,上面的替換方式就不合適了,需要將/改為#
#!/bin/bash old_str=redis new_str=/data/ sed -i 's#'''$old_str'''#'''$new_str'''#g' file
執行結果
[root@localhost work]# cat file redis [root@localhost work]# ./replace.sh [root@localhost work]# cat file /data/