Regular expression operators
When we use the ==
condition, AWK looks for an exact match. However, when we use the match operator (~
), AWK looks for a partial match. Here, ~
means contains. To match a specific pattern using regular expression, ~
and !~
are used. Regular expression comparisons are performed using a matching expression built with either of these two operators. The right-hand side of the ~
or !~
operator could be a regular expression or string enclosed between forward slashes (/…/
).
Match operator (~):
It is represented as a tilde (~
)symbol. It matches a pattern in a specific field.Its syntax is as follows:
expression ~ /regexpr/
It matches if the string value of the expression contains a sub-string matched by regular expressionregexpr.
For example, if you want to print the records containingSingh
or Kapur
in last name fieldfromthe employees database emp.dat
, use the ~
operator as follows:
$ awk '$2 ~ /(Singh|Kapur)/ { print }' emp.dat
The output on execution of the preceding code...