Home > awk > awk – Printing row totals

awk – Printing row totals

Problem:

Had various files with totals that had to be combined/totaled into one file.

From

cars,30,cars,15,cars,5
bikes,0,bikes,0,bikes,6
trains,10,trains,30,trains,15
buses,0,buses,0,buses,0

To

cars,50
bikes,6
trains,55
buses,0

Solution:

I went with awk.


paste -d, file1.txt file2.txt file3.txt  | \
cut -d, -f1,2,4,6  | \
awk -v FS="," 'total=$2+$3+$4+1 {print $1,total-1}'

NB:

Using

awk -v FS="," 'total=$2+$3+$4 {print $1,total}'

Will not return any results that have a zero. So add one to the total then remove it when printing so that you can get the zero counts.

awk -v FS="," 'total=$2+$3+$4+1 {print $1,total-1}'
Advertisements
Categories: awk Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: