简体   繁体   中英

search and replace string using sed

i have a sed command like this for search and replace string inside a file:

sed -i -e 's/`db1`./`db2`./g' result/files1.sql

that is working fine to replace the db1 to db2 inside the file of: result/files1.sql

however when i change it to bash and variable format, it does not work.

sed -i -e "s/`${mydbname}`./`${mydbname2}`./g" "${mypath}"

i get error like:

./mycoolscript: line 241: db1: command not found
./mycoolscript: line 241: db2: command not found

any solution would be great.

If is something you need to replace, you will need to escape by . Here it is

sed -i -e "s/\`${mydbname}\`./\`${mydbname2}\`./g" "${mypath}"

Escape the backtick character

sed -i -e "s/\`${mydbname}\`./\`${mydbname2}\`./g" "${mypath}"

Bash treats the part within backticks as a command and first executes that.

尝试这个

sed -i -e "s/${mydbname}/${mydbname2}/g" "${mypath}"

There is one more way, of using single quotes for literals & double quotes only around variables/escape sequences.

sed -i -e 's/`'"${mydbname}"'`./`'"${mydbname2}"'`./g' "${mypath}"

Because of single quotes, you will not have to escape the special characters.

The trade-off between escaping special characters vs. using mix of single & double quotes would depend on number of special characters vs. number of variables.

If there are too many characters that would need escaping & less number of variables, I would prefer mix of single & double quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM