Like any other programming language Awk also has lot of operators for number and string operations. In this article let us discuss about all the key awk operators.There are two types of operators in Awk.

Unary Operator – Operator which accepts single operand is called unary operator.

Binary Operator – Operator which accepts more than one operand is called binary operator.

Awk Unary Operator

Operator

Description

+

Positivate the number

-

Negate the number

++

AutoIncrement

–

AutoDecrement

Awk Binary Operator

There are different kinds of binary operators are available in Awk. It is been classified based on its usage.

Awk Arithmetic Opertors

The following operators are used for performing arithmetic calculations.

Awk Example 1: Count the total number of fields in a file.

The below awk script, matches all the lines and keeps adding the number of fields in each line,using shortcut addition assignment operator. The number of fields seen so far is kept in a variable named ‘total’. Once the input has been processed, special pattern ‘END {…}’ is executed, which prints the total number of fields.

$ awk -F ':' '{ total += NF }; END { print total }' /etc/passwd
49

Awk Example 2: Count number of users who is using /bin/sh shell

In the below awk script, it matches last field of all lines containing the pattern /bin/sh. Regular expression should be closed between //. So all the frontslash(/) has to be escaped in the regular expression. When a line matches variable ‘n’ gets incremented by one. Printed the value of the ‘n’ in the END section.

Awk Example 3: Find the user details who is having the highest USER ID

The below awk script, keeps track of the largest number in the field in variable ‘maxuid’ and the corresponding line will be stored in variable ‘maxline’. Once it has looped over all lines, it prints them out.

Awk Example 6: Print user details who has USER ID greater than or equal to 100 and who has to use /bin/sh

In the below Awk statement, there are two conditional expression one is User id($3) greater than or equal to 100, and second is last field should match with the /bin/sh , ‘&&’ is to print only if both the above conditions are true.