Awk is a powerful command, check some tutorials here. Some specific examples to your needs and for you to understand the concepts of awk
Assuming your file is named file.txt
a,5
b,2
c,3
You can use the following:
awk -F, '{print $2}' file.txt
With this you are getting "the second column" delimited by the symbol ',' from the file: file.txt
.
To sum a column, you can use the following:
awk -F, '{ total += $2; } END {print total}' file.txt
That is, use a temporary variable to accumulate each value in the second column.
Finally, you can use the following:
awk 'BEGIN{FS=OFS=","}{a[$1]+=$2}END{for(i in a)print i,a[i]}' file1 file2 ... fileN
You declare the delimiter by using a built-in
variable of awk
named OFS
which stands for, Output Field Separator Variable
, then you can do a loop adding the second column.
Note
: sort
is not needed since the sum is being done by key
. And also take into account that ... fileN
represents the N files you will send to the script.