sed use variables

sed use variables, a common approach can not resolve the variable

The presence of the current string pedis document file, which now replaced redis

[root@localhost work]# cat file 
pedis

The following two alternatives are not feasible

#!/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

The variable cause to use three single quotes, you can solve the problem

#!/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

Results of the

[root@localhost work]# cat file 
pedis
[root@localhost work]# ./replace.sh 
[root@localhost work]# cat file 
redis

 

Guess you like

Origin www.cnblogs.com/qq931399960/p/11568084.html