Monday, January 7, 2008

Match words - BASH Newbie


$ cat filea #It contains ID:Name
5:John
4:Michel
9:Rachel
100:George

$ cat fileb #It contains ID
9
100
4
5
5
4
22
9
100
100

#Replace the IDs in fileb with Names from filea, outout required

Rachel

George
Michel
John
John
Michel
NO MATCH FOUND
Rachel
George
George

$ cat fileb | while read num

> do
> NAME=`awk -F ":" '$1=="'"$num"'" {print $2}' filea`
> [ -z $NAME ] && echo "NO MATCH FOUND" || echo $NAME
> done

The above is not going to perform well if fileb is a big one, here is a good one

$ awk 'BEGIN{FS=":"}
> FNR==NR{
> array[$1]=$2
> next
> }
> { print array[$1] }' filea fileb

1 comment:

Sadhun Ganesh said...

Second example doesn't handle "NOT MATCH" scenario. Please update the script with handling the "NOT MATCH" scenario

© Jadu Saikia www.UNIXCL.com