Skip to content

"awk" command examples

Show username and its ID from /etc/passwd file:

awk -F":" '{ print $1 " " $3 }' /etc/passwd

Count empty lines:

$ cat test.awk

BEGIN { x=0 }
/^$/  { x=x+1 }
END   { print "Found " x " empty lines" }

$ awk -f test.awk input.txt

Store each 40th line from input data in a separate file:

awk '{ if (NR % 40 == 0) print $0 }' inserts.sql > inserts2.sql

Calculate min and max values for a field:

$ cat 1.txt 

abcde|123|qwert|1
abcde|123|qwert|10
ddabebnrnhcde|123|qwert|32
ddabebnrnhcde|123|qwert|312
abcde|123|qwert|142
AebnTbcde|2123|qwert|61
abcde|14523|qwert|1
abcde|2123|qwert|1
wghrehabcde|7123|qwert|81
abcde|9123|qwert|1
abcde|123|qwert|1

$ awk -F"|" 'BEGIN {n=0} {if ($2=="123") {print $2 " " $4; n=n+1; if (n==1||min>$4) min=$4; if (n==1||max<$4) max=$4}} END {print "Min=" min " Max=" max}' 1.txt 

123 1
123 10
123 32
123 312
123 142
123 1
Min=1 Max=312