sed中使用变量及变量中存在特殊字符‘/’处理

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/
原文地址:https://www.cnblogs.com/yang5726685/p/15740733.html