match records of a file with field values of another file in awk

StackOverflow https://stackoverflow.com/questions/20894945
  •  
  •  | 
  •   ( words)
 Checked

Question

I want to sum up values in a field of a CSV file where matching should be checked by reading another file, say we have CSV_file:

adam,18
denis,19
julie,17
adam,15
max,20
julie,19

and a simple txt file containing:

adam
julie

all I need is to sum up 18,15,17,19 how could I easily do that with awk?

Solution

awk 'NR==FNR{ s[$1]+= $2; next} {t+=s[$1]} END{ print t}' FS=, csv-file names.txt

OTHER TIPS

Assuming names.txt is:

adam
julie

And values.txt is:

adam,18
denis,19
julie,17
adam,15
max,20
julie,19

Then you can make use of grep's -f flag, which reads patterns from a file, one pattern per line, and returns all lines from values.txt that match any pattern. Then we just use awk to parse out the numbers and sum:

grep -f names.txt values.txt | \
awk 'BEGIN{FS=",";total=0}{total+=$2}END{print total}'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow