Wednesday, April 1, 2009

Awk Commands to remember

The
following example prints the second field of each input record whose first field is precisely
‘foo’:
$ awk '$1 == "foo" { print $2 }' filename

following regular expression match accepts any record with a first field that contains ‘foo’:
$ awk '$1 ~ /foo/ { print $2 }' filename

A regexp constant as a pattern is also a special case of an expression pattern. The
expression /foo/ has the value one if ‘foo’ appears in the current input record. Thus, as a
pattern, /foo/ matches any record containing ‘foo’.

Boolean expressions are also commonly used as patterns. Whether the pattern matches
an input record depends on whether its subexpressions match. For example, the following
command prints all the records in ‘BBS-list’ that contain both ‘2400’ and ‘foo’:
$ awk '/2400/ && /foo/' BBS-list

The following command prints all records in ‘BBS-list’ that contain either ‘2400’ or
‘foo’ (or both, of course):
$ awk '/2400/ || /foo/' BBS-list

The following command prints all records in ‘BBS-list’ that do not contain the string
‘foo’:
$ awk ’! /foo/’ BBS-list


Good Website for Awk One liners

No comments: