How to grep and cut numbers from a file and sum them

You can take help from paste to serialize the numbers in a format suitable for bc to do the addition:

% grep "30201" logfile.txt | cut -f6 -d "|"
650
1389
945

% grep "30201" logfile.txt | cut -f6 -d "|" | paste -sd+
650+1389+945

% grep "30201" logfile.txt | cut -f6 -d "|" | paste -sd+ | bc
2984

If you have grep with PCRE, you can do it with grep alone using postive lookbehind:

% grep -Po '\|30201\|.*\|\K\d+' logfile.txt | cut -f6 -d "|" | paste -sd+ | bc
2984

With awk alone:

% awk -F'|' '$3 == 30201 {sum+=$NF}; END{print sum}' logfile.txt        
2984
  • -F'|' sets the field separator as |
  • $3 == 30201 {sum+=$NF} adds up the last field's values if the third field is 30201
  • END{print sum} prints the sum at the END