1

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"
4

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

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

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'
ABC/G

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|'
ABC/G

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

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:

ABC/G

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.