Match words

I have two files

First one is as follow:

5:John
4:Michel
9:Rachel
100:George

Second file is as follow:

9
100
4
5
5
4
9
100
100

I want to process the two files to have the output.

Rachel
George
Michel
John
John
Michel
Rachel
George
George

Could any one help me to have script using bash scripting or perl?

#!/bin/sh
while read line
do
     while IFS=":" read a b
     do       
        if [ "$a" == "$line" ];then
          echo $b
        fi
     done < "file1"
done <"file2" 

Hi.

Using a shell array:

#!/usr/bin/env sh

# @(#) s2       Demonstrate saving file in array, processing based on index.

set -o nounset
echo

debug=":"
debug="echo"

## The shebang using "env" line is designed for portability. For
#  higher security, use:
#
#  #!/bin/sh -

## Use local command version for the commands in this demonstration.

echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version bash

echo

FILE1=${1-data1}
echo " Input file $FILE1:"
cat $FILE1

echo
FILE2=${1-data2}
echo " Input file $FILE2:"
cat $FILE2

echo
echo " Results from processing:"

while IFS=":" read a b
do
  content[$a]="$b"
done <$FILE1

while read a
do
  echo ${content[$a]}
done <$FILE2

exit 0

Producing:

% ./s2

(Versions displayed with local utility "version")
GNU bash 2.05b.0

 Input file data1:
5:John
4:Michel
9:Rachel
100:George

 Input file data2:
9
100
4
5
5
4
9
100
100

 Results from processing:
Rachel
George
Michel
John
John
Michel
Rachel
George
George

See http://www.tldp.org/LDP/abs/html/arrays.html\#EX66 for examples of array use .... cheers, drl

Since OP is Open2Perl :slight_smile:

#!/usr/bin/perl

my %lookup;
my $main = pop @ARGV;
while (<>) {
        split /:/;
        $lookup{$_[0]} = $_[1];
}

@ARGV = ($main);
while (<>) {
        chomp;
        exists($lookup{$_}) and print $lookup{$_};
}

Output:

$ cat file.1
5:John
4:Michel
9:Rachel
100:George

$ cat file.2
9
100
4
5
5
4
9
100
100

$ l.pl file.1 file.2
Rachel
George
Michel
John
John
Michel
Rachel
George
George

I'm sure this can made cleaner/tighter in perl (I'm out of touch with perl).

HTH

A small one (in one line)

$ cat fileb | while read num
> do
> awk -F ":" '$1=="'"$num"'" {print $2}' filea
> done

And If you want to check for "NO MATCH FOUND" in filea(first file)

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

//Jadu

If the filesize is small, anything goes :slight_smile:

use nawk on Solaris

awk 'BEGIN{FS=":"}
FNR==NR{
  array[$1]=$2
  next
}
{ print array[$1] }' file file1

will not perform well for very large fileb.

Agree :slight_smile: Thanks