I want to write a small tool or Bash function that can be used like:
tool foo bar file
and it should replace all occurrences of foo in file with bar.
The key problem for me: both foo and bar can be arbitrary strings, possibly containing symbols or characters that have special meaning in regex or something of sed, awk, etc.
So tools like sed fail for me
Is there a simple way to do this in Bash? The simpler the better.
Thanks in advance!
I tried:
sed -i "s/${key}/${value}/g" file
and
body="$(cat file)"
body="${body//${key}/${value}}"
and
body="$( awk -v "key=${key}" -v "value=${value}" 'BEGIN { gsub(/\$/, "\\$", key) }{ gsub(key, value); print }' file )"
But none is good enough.