Justin
Justin

Reputation: 45350

Bash Sed Find & Replace With Special Characters

I am trying to find {AUTH-KEYS-SALTS} in the file wp-config.php and replace it with the contents of the bash variable keysalts.

keysalts=`curl -sS https://api.wordpress.org/secret-key/1.1/salt/`
sed -i "s/{AUTH-KEYS-SALTS}/$keysalts/g" wp-config.php

The following almost works, except that keysalts has a bunch of special characters such as $`;'" and sed is getting confused. Basically, how do I escape everything and just replace {AUTH-KEYS-SALTS} with $keysalts?

Thanks.

Upvotes: 3

Views: 3375

Answers (4)

Dennis Estenson
Dennis Estenson

Reputation: 1092

It turns out you're asking the wrong question. I also asked the wrong question. The reason it's wrong is the beginning of the first sentence: "In my bash script...".

I had the same question & made the same mistake. If you're using bash, you don't need to use sed to do string replacements (and it's much cleaner to use the replace feature built into bash).

Instead of:

  keysalts=`curl -sS https://api.wordpress.org/secret-key/1.1/salt/`
  sed -i "s/{AUTH-KEYS-SALTS}/$keysalts/g" wp-config.php

you can use bash features exclusively, reading the file into a variable, replacing the text in the variable, and writing the replaced text back out to the file:

  INPUT=$(<wp-config.php)
  keysalts="$(curl -sS https://api.wordpress.org/secret-key/1.1/salt/)"
  echo "${INPUT//'{AUTH-KEYS-SALTS}'/"$keysalts"}" >wp-config.php

Upvotes: 1

macduff
macduff

Reputation: 4685

Actually, I like this one better

sed -i 's/{AUTH-KEYS-SALTS}/'"$keysalts"'/g' wp-config.php

Personal choice. :-)

Upvotes: 1

Birei
Birei

Reputation: 36262

Other way could be using perl:

perl -i -pe '
  BEGIN { 
    $keysalts = qx(curl -sS https://api.wordpress.org/secret-key/1.1/salt) 
  } 
  s/{AUTH-KEYS-SALTS}/$keysalts/g
' wp-config.php

Upvotes: 3

Eduardo Ivanec
Eduardo Ivanec

Reputation: 11862

You can escape $keysalts using sed itself:

sed -i "s/{AUTH-KEYS-SALTS}/`echo $keysalts | sed -e 's/[\/&]/\\&/g'`/g" wp-config.php

See this question for more information.

Upvotes: 2

Related Questions