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.

1 Reply 1

The question would be more objective if you posted your attempted solution. Otherwise, the question looks like "do my work for me".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.