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?

有帮助吗?

解决方案

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

其他提示

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}'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top