Matching with awk

here is a very simple cool trick. Imagine you would have a file (test.txt) with a few million lines in it looking something like this:

abc 123 def
ghi 123 jkl
mno 456 pqr

Imagine you would like to know how many lines there are with "123" in the second column. try something like this:

cat test.txt | awk 'match ($2,/123/)' | wc -l

This will open the file test.txt ("cat test.txt") and give the results to awk ("|awk"). awk will look for 123 in column 2. ("match ($2,/123/)". these results are passed to wc, a counter, that can count lines with the -l option. ("| wc -l")

Think of another example; you'd like to find all pids where the connected tty is ttys000:

ps -ef | awk '{ if ($6 == "ttys000") print $1 }'

About Consultancy Articles Contact




References Red Hat Certified Architect By Robert de Bock Robert de Bock
Curriculum Vitae By Fred Clausen +31 6 14 39 58 72
By Nelson Manning [email protected]