Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to escape parentheses in awk string constant?

Tags:

awk

consider a simple file named test containing the following text:

abc(def)

With awk, if I found out that this will work:

awk '$0 ~ "abc\(def\)"' test

but it won't work if the parentheses are not properly escaped:

awk '$0 ~ "abc(def)"' test

Dropping the right parenthesis, I got this error:

awk: line 1: regular expression compile failed (missing ')')
abc(def

Isn't string quoted by "" string constant in awk? Why are () treated as regular expression special character in a string constant?

like image 759
Naitree Avatar asked Nov 05 '25 08:11

Naitree


2 Answers

If I correctly understood the question, then the answer is something like this:

awk -F ',' '{ print "(" $1, $2 ")" }'

You should type ( between " ". Any special symbols you may print with " "

like image 80
frops Avatar answered Nov 07 '25 22:11

frops


When looking at the documentation of gawk here, it says (emphasis mine)

Regexp matching and non-matching are also very common expressions. The left operand of the ~ and !~ operators is a string. The right operand is either a constant regular expression enclosed in slashes (/regexp/), or any expression, whose string value is used as a dynamic regular expression (see section Using Dynamic Regexps).

Regexp constants are created when running the script and can not be changed during the run of the program while dynamic regular expressions can be changed by the script.

like image 23
martin Avatar answered Nov 07 '25 21:11

martin