Learning AWK Programming
上QQ阅读APP看书,第一时间看更新

Alternation operator

The alternation operator is used to specify alternatives. The alternation operator is a vertical bar or pipe symbol, it matches one regular expression out of several regular expressions. The '|' alternation operator has the lowest precedence among all the regular expression operators. For example, in the employee database, if we want to print the lines that have first name of the employee as EmilyJack, or Ana, we can write the following regular expression:

$ awk '/Emily|Jack|Ana/' emp.dat

In AWK, it is generally used with the ( ) grouping operator, as follows:

$ awk '/(Emily|Jack|Ana)/' emp.dat

The output on execution of the given code is as follows:

Jack    Singh   9857532312  jack@gmail.com      M   hr      2000
Ana Khanna 9856422312 anak@hotmail.com F Ops 2700
Emily Kaur 8826175812 emily@gmail.com F Ops 2100

With the alternation operator, we can combine multiple regular expressions together, as follows:

$ awk '/^J|^V/' emp.dat

The output on execution of the preceding code is as follows:

Jack    Singh   9857532312  jack@gmail.com      M   hr      2000
Jane Kaur 9837432312 jane@gmail.com F hr 1800
Julie Kapur 8826234556 julie@yahoo.com F Ops 2500
Victor Sharma 8826567898 vics@hotmail.com M Ops 2500
John Kapur 9911556789 john@gmail.com M hr 2200
Vina Singh 8811776612 vina@yahoo.com F lgs 2300

So, in the previous example, we could print the employee details for those whose first name begins with J or V.

The alternation applies to the largest possible regular expressions on either side. For example, if we want to print the lines that begin with either J or V, or the email ID of users beginning with v, as follows:

$ awk '/(^J|^V)|($4 ~ ^v)/' emp.dat

The output on execution of the preceding code is as follows:

Jack    Singh   9857532312  jack@gmail.com      M   hr      2000
Jane Kaur 9837432312 jane@gmail.com F hr 1800
Julie Kapur 8826234556 julie@yahoo.com F Ops 2500
Victor Sharma 8826567898 vics@hotmail.com M Ops 2500
John Kapur 9911556789 john@gmail.com M hr 2200
Vina Singh 8811776612 vina@yahoo.com F lgs 2300