Reputation: 13
I have a file that looks like this :
A B C 128 D
Z F R 18 -
M W A 1 -
T B D 21 P
Z F R 11 -
L W A 10 D
I am looking for a way to sum up the column 4 ( for the lines witch column 5 look like D) here in this example will be: 128 + 10 = 138 .
I managed to sum up all the 4th column with this command :
cat file.txt |awk '{total+= $4} END {print total}'
Upvotes: 1
Views: 83
Reputation: 2091
A solution with datamash
and sort
:
cat file.txt | sort -k5 | datamash -W -g5 sum 4
sort -k5
for sorting according the 5
column.datamash
uses -W
to specify that whitespace is the separator, -g5
to group by 5th
column, and finally sum 4
to get sum of 4th
column.It gives this output:
- 30
D 138
P 21
Upvotes: 1
Reputation: 531165
You just omitted the pattern to select which lines your action applies to.
awk '$5 == "D" {total += $4} END {print total}' file.txt
In awk
, the pattern is applied to each line of input, and if the pattern matches, the action is applied. If there is no pattern (as in your attempt), the line is unconditionally processed.
Upvotes: 3