Hi how can I use gsub to replace a word which has parentheses.

Here I want to replace ABC(T) with ABC/G

awk ' {gsub("ABC\(T\)","ABC/G")}; Print $0' "$FILENAME" > tmp.tmp && mv tmp.tmp "$FILENAME"

You could simplify the whole thing if you use the // format for gsub:

$ echo "ABC(T)" | awk '{gsub(/ABC\(T\)/,"ABC/G")}; print $0'

Then, you could simplify further by using print with no arguments (which is the same as print $0) or the 1 shorthand for printing (the default awk action for expressions that evaluate to true, such as 1; is to print the current line):

$ echo "ABC(T)" | awk '{gsub(/ABC\(T\)/,"ABC/G")}1'

Personally, however, I wouldn't use awk for this, the syntax is shorter and cleaner with other tools:

$ echo "ABC(T)" | sed 's|ABC(T)|ABC/G|'

$ echo "ABC(T)" | perl -pe 's|ABC\(T\)|ABC/G|'

You were very close. You just needed two \. That is because one of set is for the text itself passing through BASH, and the other would be the actual \ which is being parsed by awk. This seems to work for me:

echo 'ABC(T)' | awk ' {gsub("ABC\\(T\\)","ABC/G")}; Print $0' "$FILENAME"

And gives:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.