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/


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM