Get information from one files, based on data from other file

Hello.

I am trying to get some info from log file.

I have fileA , which contains all the country prefixes (the file contains one column and "n" rows ).

And i have fileB, which contains huge data of phone numbers (the file contains one column and "n" rows).

What i want to do is, to count how many phone calls we have made to certain country (prefix).
For example :

If fileA contains:

44
39
359                 

And fileB contains:

44858475648
44645645645
3943534534          

The output should be:

                                44 - 2 times
                                39 - 1 time 
       

Any help would be appreciate.

Regards,
DF

The lazy way if you just have to run it once.

while read cc
do
   echo $cc $(grep -c "^$cc" fileb)
done <filea

If you have to run this frequently, or the number of records in filea is large then you may want to first sort fileb and create a "rolling totals" type program.

2 Likes

or:

 awk 'FNR==NR {a[$1];next} {for(i in a) if ($0 ~ ("^"i)) a++}END {for (i in a) printf("%d - %d times\n", i, a)}' fileA fileB
2 Likes

Supress showing the zero matches:

while read cc
do
   c=$(grep -c "^$cc" fileb) &&
   echo "$cc - $c times"
done <filea
...
 END {for (i in a) if (a) printf("%d - %d times\n", i, a)}
' fileA fileB
1 Like

Single grep approach:

sed 's/^/^/' filea | grep  -of- fileb | sort | uniq -c
      1 39
      2 44

You can drop the sort if fileb is already sorted.

2 Likes

Thanks a lot guys.

With sed and awk examples, it worked like a charm.
I couldnt do it with "while do" , but i will keep trying.

Once again, thanks to everyone.

Post the "while do" that you are struggling with for analysis / help.

As soon as i read more and dig deeper about "while do", i will bombard you with questions :wink:

Thanks again.