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

3 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.

Karan Bohra said...

#!/bin/sh -u


results='results.classV.txt'

student=${1:-'Naveen'}

unset hdr_eko

nop=':'

while IFS= read -r Line
do
set -f; IFS=':,'; set -- $Line
case "$*" in
*":$student:"* )
${hdr_eko+"$nop"} echo "$student"
game=$1; shift; hdr_eko=
while case $# in 0 ) break;; esac
do
case $1 in "$student" ) echo "$game:$2"; break;; esac
shift
done;;
esac
done < $results


sed -n '
s/:\(.*,\)\{0,1\}'"$student"',\([^,]*\).*/:\2/;T
G;/\n./{P;d;}
s/^/'"$student"'\n/;s/.$//p;h
' < $results

perl -F'[:,]' -slane '
print($flag++ ? "" : "$student\n", "$F[0]:$1") if /[:,]$student,([^,]+)/;

# Or this,
#grep {$F[$_-1] eq $student and $a=$_ } 1..@F and print($flag++ ? "" : "$student\n", "$F[0]:$F[$a]");

' -- -student="$student" < $results

© Jadu Saikia www.UNIXCL.com