Thursday, March 13, 2008

Pattern not found - AWK


Sample file "cscbatch04" is the details of students of Computer Science 2004 batch of JEC.


$ cat cscbatch04.txt
Mr A,26,C1,C2
Mr B,25,C1,C1
Mr C,25,C3,C1
Mr D,25,C4,C2

Purpose: Search a pattern as the 3rd field in all the lines of the file cscbatch04.txt.
- If the pattern is found, list the lines where it is present as the 3rd field
- If the pattern is not found as 3rd field in any of the lines, echo a message telling "not found"

Here lies the AWK solution:

Searching the pattern "C1" which is present as 3rd field in cscbatch04.txt.
$ awk 'END { if (!found) print "pattern not found" }
$3 == "C1" { print "pattern found in line:", NR; found++ }
' FS="," cscbatch04.txt

pattern found in line: 1
pattern found in line: 2


Searching the pattern "C2" which is not present as "3rd field" in cscbatch04.txt.
$ awk 'END { if (!found) print "pattern not found" }
$3 == "C2" { print "pattern found in line:", NR; found++ }
' FS="," cscbatch04.txt

pattern not found

No comments:

© Jadu Saikia www.UNIXCL.com