Bash script find and replace string with variable that contains complex special characters without having to escape?

Issue

Is there a simpler way to replace a string with a variable literally that contains all complex characters without needing to do character escaping?

complex='~`[email protected]#$%^&*()-_=+\|]}{[;:/?.>,<\/*&\#/'
sed -i "s/secret\ =\ \".*/secret\ =\ \"$complex\"/g" ./file.txt

I already know that & \ and / are the problems. I can do all manner of cleaning with sed commands, but is there a simpler way? Is there a way I can literally make sed read that variable as is?

My work around for now is the following, but even this does not work with / properly …

complex='~`[email protected]#$%^&*()-_=+\|]}{[;:/?.>,<\/*&\#/'
psk_bs="$(echo $complex | sed 's/\\/\\\\\\/g')"
psk_bs_amp="$(echo "$psk_bs" | sed 's/\&/\\&/g')"
psk_bs_amp_fs="$(echo "$psk_bs_amp" | sed 's,'/','\/',g')"
sed -i "s/secret\ =\ \".*/secret\ =\ \"$psk_bs_amp_fs\"/g" ./file.txt

Solution

I can do all manner of cleaning with sed commands, but is there a simpler way? Is there a way I can literally make sed read that variable as is?

I’m afraid there is not. But character escaping is not as a big deal as you make it seem to be. This’ll work just fine:

psk=$(sed 's/[/&\]/\\&/g' <<< $complex)
sed -i "s/secret = \".*/secret = \"$psk\"/g" ./file.txt

With bash 5.2 you don’t even need sed for escaping:

psk=${complex//[\/&\\]/\\&}

Answered By – oguz ismail

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published