Matching at the beginning of a string
The unquoted caret ^ matches the string at the beginning of line. The ^ is only the anchor if it is the first character in the regular expression. For example, we use the /^J/ regular expression to match all the lines that begin with J. It will print the employee information of those whose first name begins with the J character in the employee database:
$ awk '/^J/{ print }' 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
John Kapur 9911556789 john@gmail.com M hr 2200
We can also use the anchor, ^ (caret), with the string match operator (~) to match the field beginning with a specified character. In the following example, we print all the lines whose second field begins with S. It will print employee information for those employees whose last name begins with the S character, as follows:
$ awk '$2 ~ /^S/{ print }' emp.dat
The output on execution of the preceding code is as follows:
Jack Singh 9857532312 jack@gmail.com M hr 2000
Amit Sharma 9911887766 amit@yahoo.com M lgs 2350
Hari Singh 8827255666 hari@yahoo.com M Ops 2350
Victor Sharma 8826567898 vics@hotmail.com M Ops 2500
Ginny Singh 9857123466 ginny@yahoo.com F hr 2250
Amy Sharma 9857536898 amys@hotmail.com F Ops 2500
Vina Singh 8811776612 vina@yahoo.com F lgs 2300