So, the question is pretty straightforward : In awk, is if ( var ~ /pattern/ ) the same as if ( var ~ "pattern" ) ?
I've done some basic test on a csv, and both seems to yield the same result... Is there any subtle difference I've missed ?
So, the question is pretty straightforward : In awk, is if ( var ~ /pattern/ ) the same as if ( var ~ "pattern" ) ?
I've done some basic test on a csv, and both seems to yield the same result... Is there any subtle difference I've missed ?
This is very well explained in GNU awk docs under 3.6 Using Dynamic Regexps
NOTE: When using the~and!~operators, be aware that there is a difference between a regexp constant enclosed in slashes and a string constant enclosed in double quotes. If you are going to use a string constant, you have to understand that the string is, in essence, scanned twice: the first time whenawkreads your program, and the second time when it goes to match the string on the lefthand side of the operator with the pattern on the right.What difference does it make if the string is scanned twice? The answer has to do with escape sequences, and particularly with backslashes. To get a backslash into a regular expression inside a string,
you have to type two backslashes.
A simple demonstrative example to explain the difference. When using a regexp constant
echo 'foo*bar dude' | awk '$1 ~ /foo\*bar/'
and with dynamic regexp string, because the regexp string under ".." undergoes scanning twice, you need an additional \ to escape the \ added for *
echo 'foo*bar dude' | awk '$1 ~ "foo\\*bar"'
All the backslash escape sequence characters undergo this special handling when using dynamic regexps. For e.g. to escape a \n in the line
echo 'foo\nbar dude' | awk '$1 ~ /foo\\nbar/'
and
echo 'foo\nbar dude' | awk '$1 ~ "foo\\\\nbar"'
The documentation also clearly explains which one to use
String constants are more complicated to write and more difficult to read. Using regexp constants makes your programs less error-prone. Not understanding the difference between the two kinds of constants is a common source of errors.
It is more efficient to use regexp constants.
awkcan note that you have supplied a regexp and store it internally in a form that makes pattern matching more efficient. When using a string constant, awk must first convert the string into this internal form and then perform the pattern matching.Using regexp constants is better form; it shows clearly that you intend a regexp match.