awk '
# Create an associative array: A for which value is sum of $2 and indexed by $1
{
A[$1] += $2
}
# End Block
END {
# For each element in associative array: A
for ( k in A )
# Print index & value of
print k, A[k]
}
# Path name expansion (aka globbing) will help open & read all files with file name prefixed: file
' file*
When I run these codes it seems to sum the values of second column properly but they go out of order. Is there a way to generate them in order or to put them in order again?
If you want to disregard the first column, just print the sum:
print A[k]
By default, the order in which a for (i in array) loop scans an array is not defined; it is generally based upon the internal implementation of arrays inside awk.
You might have to use an indexed array to preserve the order.
Could you please explain the use of END here as if we are not using END it is giving some thing else result, will be grateful to you if you throw some light on same.
awk '
# Create an associative array: A for which value is sum of $2 and indexed by $1
{
A[$1] += $2
}
# End Block
END {
# For each element in associative array: A
for ( k in A )
# Print index & value of
print k, A[k]
}
# Path name expansion (aka globbing) will help open & read all files with file name prefixed: file
' file*