Replace Text Between Brackets Using Sed or Awk

awkregular expressionreplacesedtext processing

I'm using awk '{ gsub(/BAR|WIBBLE/, "FOO"); print }' to replace text in data like:

SOMETHING [BAR, WIBBLE]
SOMETHING [BAR]

This gives the desired result of:

SOMETHING [FOO, FOO]
SOMETHING [FOO]

But now I've had to update the text that requires replacing to be something like:

awk '{ gsub(/BAR|WIBBLE|ME/, "FOO"); print }'

Which turns text like:

SOMETHING [ME, WIBBLE]

into:

SOFOOTHING [FOO, FOO]

How can I limit my replacement to just the text between the brackets (i.e. leave the SOMETHING alone)?

EDIT

I also need robustness across whatever text SOMETHING might be (e.g. SHE GAVE ME THAT shouldn't have ME replaced).

Best Answer

Must that be awk? Is much easier in other languages where the substitution's replacement part can be a function call. For example perl:

perl -pe 'sub c{$s=shift;$s=~s/BAR|WIBBLE|ME/FOO/g;$s}s/\[.*?\]/c$&/ge' 
Related Question