Wednesday, December 16, 2009

Awk - Print next column after pattern


Input file 'results.classV.txt' contains the results of class V students in the School annual sports meet.

$ cat results.classV.txt
Chess:Alex,First,Naveen,Second,Lee,4th
Carrom:Naveen,First
billiards:Lee,First,Nill,Second
foosball:Nill,First,Naveen,4th
badminton:Lee,Second

i.e. the name of a student precedes his rank in a game.

Required:

Extract out the details of student "Naveen" in each game.

The awk solution:

$ awk '
BEGIN {FS="[:,,]"; OFS=":"; {print "Naveen"}}
{ for(j=0;j<=NF;j++)
if ( $j == "Naveen" )
print $1,$(j+1)}
' results.classV.txt

Output:

Naveen
Chess:Second
Carrom:First
foosball:4th

Related posts:

- Find blank columns in a file using awk
- Find column number based on field header using awk
- Print range of columns using awk
- Awk - find column number of a pattern

2 comments:

Mahesh Kharvi said...

We can try something like this in sed

sed -ne '/Naveen/ s/\(:.*Naveen,\)\([[:alnum:]]*\)\(.*\)/:\2/gp'

Jadu Saikia said...

@Mahesh, this one using sed is useful. Thanks.

© Jadu Saikia www.UNIXCL.com