awk

awk

•fields
$0 whole line
$1 1st field
$2 2nd field
NF number of fields
NR number of records

•pattern operators
==
!=
< <= >=
?:

•Punctuation
{}
$
~ contains
!~ not contain
, separate things in “print”
; separate statements
// used around regular expression
() grouping

•they are same
awk ‘$1 > $2’
awk ‘$1 > $2{print}’
awk ‘$1 > $2{print $0}’

§samples
•Print second field then first
awk ‘{print $2,$1}’ file

•Checks for matching string:
awk ‘$1==”foo”{print $2}’ file

•Search all lines that contain foo*.bar
awk ‘/foo*.bar/{print $1,$3}’ file

•foo occurs in second field
awk ‘$2~/foo/{print $3,$1}’ file

•foo not occur in second field
awk ‘$2!~/foo/{print $3,$1}’ file

•Prints all lines between and including lines that contain foo and bar
awk ‘/foo/,/bar/’ file

•Prints running total of 5th column
ls -l | awk ‘{print x+=$5,$0}’

§BEGIN and END
•awk ‘BEGIN{print “fee”} $1==”foo” {print “fi”} END {print “foo fum”}’ filename

§awk variables
•Field separater
awk -F: ‘{print $1,$3}’ /etc/passwd

•Delete 10th field from each line
awk ‘{$10=””; print}’ filename

•C like for, while, do-while, if
awk ‘{for(i=1;i

This entry was posted in shell, unix. Bookmark the permalink.