Based on the example file, steeldriver’s answer
(using a lookup table / associative array in awk)
is probably the best solution.
While it is generally inadvisable, you can do the same thing purely in bash:
declare -A id
while IFS=" ," read x idnum xx name
do
id[$name]=$idnum
done < file1
while read name
do
printf '%s %s\n' "${id[$name]}" "$name"
done < file2
The logic is the same:
- A first pass, which creates an array,
indexed by name values, containing ID values.
- A second pass, which maps names to IDs and outputs them side by side.
My answer works as desired (i.e., as specified)
for the sample data in the question.
(Since it uses an array — specifically, an associative array —
it requires bash (or ksh, zsh or yash);
arrays are not specified by the POSIX specification for the shell,
and are not available in all shells that are used in Unix/Linux.)
Because of the way bash’s read command works,
my answer also handles multi-word names (i.e., names with spaces in them)
as one might intuitively expect:
file1 file2 output
ID: 42, Name: fat cat fat cat 42 fat cat
ID: 95, Name: Superman under dog 83 under dog
ID: 83, Name: under dog spider man ⟹ 17 spider man
ID: 9, Name: cat woman spider pig 60 spider pig
ID: 17, Name: spider man Superman 95 Superman
ID: 60, Name: spider pig cat woman 9 cat woman
Note that both answers are case-sensitive;
e.g., foo1.bar.com would not match Foo1.bar.com.