Matching at the end of a string
The unquoted dollar, $, matches the string at the end of the line. The '$' is only the anchor if it is the last character in the regular expression. For example, '0$' matches all the lines that end with 0. It will print employee details of those whose salary ends with the '0' character in the employee database:
$ awk '/0$/{ print }' emp.dat
The output on execution of this code is as follows:
Jack Singh 9857532312 jack@gmail.com M hr 2000
Jane Kaur 9837432312 jane@gmail.com F hr 1800
Eva Chabra 8827232115 eva@gmail.com F lgs 2100
Amit Sharma 9911887766 amit@yahoo.com M lgs 2350
Julie Kapur 8826234556 julie@yahoo.com F Ops 2500
Ana Khanna 9856422312 anak@hotmail.com F Ops 2700
Hari Singh 8827255666 hari@yahoo.com M Ops 2350
Victor Sharma 8826567898 vics@hotmail.com M Ops 2500
John Kapur 9911556789 john@gmail.com M hr 2200
Billy Chabra 9911664321 bily@yahoo.com M lgs 1900
Sam khanna 8856345512 sam@hotmail.com F lgs 2300
Ginny Singh 9857123466 ginny@yahoo.com F hr 2250
Emily Kaur 8826175812 emily@gmail.com F Ops 2100
Amy Sharma 9857536898 amys@hotmail.com F Ops 2500
Vina Singh 8811776612 vina@yahoo.com F lgs 2300
Like ^, we can also use anchor, $ (dollar), with the string match operator (~) to match the field ending with a specific character. In the following example, we print all the lines whose second field ends with the 'a' letter, as follows:
$ awk '$2 ~ /a$/{ print }' emp.dat
The output on execution of this code is as follows:
Eva Chabra 8827232115 eva@gmail.com F lgs 2100
Amit Sharma 9911887766 amit@yahoo.com M lgs 2350
Ana Khanna 9856422312 anak@hotmail.com F Ops 2700
Victor Sharma 8826567898 vics@hotmail.com M Ops 2500
Billy Chabra 9911664321 bily@yahoo.com M lgs 1900
Sam khanna 8856345512 sam@hotmail.com F lgs 2300
Amy Sharma 9857536898 amys@hotmail.com F Ops 2500
A summary of the anchors is as follows:
Pattern |
Matches |
^C |
Matches "C" at the beginning of a line |
C$ |
Matches "C" at the end of a line |
C^ |
Matches "C^" anywhere on a line |
$C |
Matches "$C" anywhere on a line |
^C$ |
Matches the string consisting of a single "C" character |
^^ |
Matches "^" at the beginning of a line |
$$ |
Matches "$" at the end of a line |
^$ |
Matches an empty line (which begins and ends immediately) |