awk /regex/: Filter Lines by Pattern
awk runs its action only on lines that match the pattern, so /ERROR/ behaves like grep but with field access.
A bare /regex/ pattern is grep; /regex/{print $2} is grep that also extracts a column. The ~ operator matches a regex against a specific field.
What it does
A pattern before a block restricts the block to matching lines. /regex/ tests the whole line ($0); $3 ~ /regex/ tests one field; !~ negates the match. With no block, a matching line is printed, exactly like grep.
Common usage
# grep-like: print lines containing ERROR
awk '/ERROR/' build.log
# match in a field and print another column
awk '$3 ~ /FAIL/ {print $1}' results.txt
# negate: lines where field 2 is not OK
awk '$2 !~ /OK/' status.txt
# anchored match on the whole line
awk '/^WARN/{print}' app.logPattern forms
| Form | What it does |
|---|---|
| /re/ | Match the regex against the whole line ($0) |
| $3 ~ /re/ | True if field 3 matches the regex |
| $2 !~ /re/ | True if field 2 does not match |
| /^WARN/ | Anchor: line begins with WARN |
| /error$/ | Anchor: line ends with error |
| /a|b/ | Alternation: matches a or b |
In CI
awk '/ERROR/{print $NF}' both filters and extracts in one pass, saving a grep | awk pipeline. To count matches, /ERROR/{n++} END{print n} is cleaner than grep -c when you also need field values from the same lines.
Common errors in CI
"awk: syntax error at source line 1" near a regex usually means an unescaped slash inside the pattern; escape it as /\// or use a string with ~. mawk and gawk differ on some regex extensions, so a pattern using \d (which awk does not support) matches a literal d, not a digit; use [0-9] instead. A shell-expanded $ inside an unquoted program also breaks the regex.