#!/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
#!/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).