Identical Identical - 2 months ago 15
Linux Question

Using awk and grep to add up

If I had a file that looks like this:

23.00 33.44 abcd 44.44 abcd12345abcd
33.00 22.22 qt 44.00 zlkm12345ksda


and I wanted to add up the first column whenever I encounter 12345 in the middle of the pattern in the fourth column , how would I go about doing that

Answer

Something like this?

awk '$5 ~ /12345/ { TOT = TOT + $1 } END { print TOT + 0 }' yourFile.txt

(Not at a computer, so my syntax might be a bit off.)

The first bit selects the lines you want and updates the total while the END bit just prints what's accumulated.

No grep needed (for almost all intents and purposes, awk is just as good if not better), and the search is limited to just the column you want searched.