Basic AWK usage in BASH

To print a field from a file (-F is the field separator and $ is the number of the field to print):

awk -F':' '{ print $1 }' /etc/passwd or
awk -F':' '{ print $1 $3 }' /etc/passwd or
awk -F':' '{ print "username: " $1 "\t\tuid:" $3" }' /etc/passwd

For pattern matching, for example, printing httplogs with a 200 http code. ( $0 means print everything):

awk '$9 == 200 { print $0}' /var/www/vhosts/domainname/statistics/logs/access_log

To print lines with one of several strings:

awk '/user1|user2|user3/' /etc/passwd

To print a line number

awk "NR==2{print;exit}" /etc/passwd

The begin and end tags can be used to print data between each line read. For example a title and footer:

awk 'BEGIN {print "Name\tDesignation\tDepartment\tSalary";} {print $2,"\t",$3,"\t",$4,"\t",$NF;} END{print "Report Generated\n--------------"; }' employee.txt
Name Designation Department Salary
Thomas Manager Sales $5,000
Jason Developer Technology $5,500
Sanjay Sysadmin Technology $7,000
Nisha Manager Marketing $9,500
Randy DBA Technology $6,000
Report Generated
————–

AWK if / else /elseif can also be very handy:

cat grade.awk
{
total=$3+$4+$5;
avg=total/3;
if ( avg >= 90 ) grade="A";
else if ( avg >= 80) grade ="B";
else if (avg >= 70) grade ="C";
else grade="D";

print $0,"=>",grade;
}
$ awk -f grade.awk student-marks

Jones 2143 78 84 77 => C
Gondrol 2321 56 58 45 => D
RinRao 2122 38 37 => D
Edwin 2537 87 97 95 => A
Dayan 2415 30 47 => D

You can leave a response, or trackback from your own site.

Leave a Reply