Home > awk > “Generating summary data with awk

“Generating summary data with awk

Problem: A collegue asked me to do this. Generating a summary based on the week numbers. File input

$ less file1.txt
2013-03-01, Week 1, 20
2013-03-05, Week 1, 30
2013-03-04, Week 1, 20
2013-03-17, Week 1, 30
2013-03-19, Week 1, 40
2013-03-21, Week 1, 50
2013-03-01, Week 2, 20
2013-03-05, Week 2, 30
2013-03-04, Week 2, 20
2013-03-17, Week 2, 30
2013-03-19, Week 2, 40

File output

2013-03-01, 20, Week 1
2013-03-04, 20, Week 1
2013-03-05, 30, Week 1
2013-03-17, 30, Week 1
2013-03-19, 40, Week 1
2013-03-21, 50, Week 1
Total,190, Week 1
2013-03-01, 20, Week 2
2013-03-04, 20, Week 2
2013-03-05, 30, Week 2
2013-03-17, 30, Week 2
2013-03-19, 40, Week 2
Total,140, Week 2

Solution: Using awk.

$ awk -v FS="," -v OFS="," '{sum[$2]+= $3; print $1, $3, $2}
END {for (var in sum){print "Total", sum[var], var}}' file1.txt | sort -t, -k3
2013-03-01, 20, Week 1
2013-03-04, 20, Week 1
2013-03-05, 30, Week 1
2013-03-17, 30, Week 1
2013-03-19, 40, Week 1
2013-03-21, 50, Week 1
Total,190, Week 1
2013-03-01, 20, Week 2
2013-03-04, 20, Week 2
2013-03-05, 30, Week 2
2013-03-17, 30, Week 2
2013-03-19, 40, Week 2
Total,140, Week 2

Source: http://www.unix.com/shell-programming-scripting/245209-generating-summary-data-use-awk.html

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