Awk, gsub, ampersands and unexpected expansion Awk, gsub, ampersands and unexpected expansion shell shell

Awk, gsub, ampersands and unexpected expansion


& is a backreference metacharacter in many tools and it means "the string that matched the regexp you searched for". If you're trying to use literal strings then use literal strings instead of regexps and backreferences.

e.g.:

code="if (A & B)"awk -v old="REPLACE" -v new="$code" 's=index($0,old){$0=substr($0,1,s-1) new substr($0,s+length(old))} 1' test.txt

The alternative, trying to santize regexps and replacements, is complicated and error prone and generally is not for the faint of heart, see: Is it possible to escape regex metacharacters reliably with sed