1

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.

1
  • 1
    Why do you need to add ` around ${mydbname} ? It makes the second sed commands think db1 is a command rather than a string you want to replace. Note that shell will replace any variables including COMMAND inside "" (quote), but will not replace inside '' (single quote). Commented Oct 17, 2013 at 6:46

4 Answers 4

3

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

sed -i -e "s/\`${mydbname}\`./\`${mydbname2}\`./g" "${mypath}"
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

Try this

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.