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='~`!@#$%^&*()-_=+\|]}{[;:/?.>,<\/*&\#/'
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='~`!@#$%^&*()-_=+\|]}{[;:/?.>,<\/*&\#/'
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 Answer Checked By - Marie Seifert (WPSolving Admin)