Sed - replacing a string with a variable full of weird characters Sed - replacing a string with a variable full of weird characters unix unix

Sed - replacing a string with a variable full of weird characters


sed is an excellent tool for simple substitutions on a single line but for anything else you should use awk:

awk -v key="$KEY" '{sub(/stringtoreplace/,key)}1' file

That will work no matter what characters "$KEY" contains, except for "&".


One possibility is to use bash instead of sed. That makes the substitution easy, but you'll have to emulate the -i option.

Something like this:

TMPFILE=$(mktemp)KEY=$(cat keyfile)while IFS= read -r LINE; do  echo "${LINE//stringtoreplace/$KEY}"done </path/to/file >$TMPFILEmv $TMPFILE /path/to/file


Try this:

KEY=$(cat keyfile | sed -e 's/[]\/()$*.^|[]/\\&/g')sed -i "s/stringtoreplace/$KEY/" /path/to/file