Solved

# average data in third column per month and round to the nearest hundredth

Posted on 2012-03-15
309 Views
I have a file called output.txt and I want to average data per month. The original attached file should create month in the first column average value in the second column. Each row should look like this below. The averages are bogus just for example. See attached file.

output2.txt sample file rows with bogus data.
198001 120.22
198002 133.42
output.txt
0
Question by:libertyforall2
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 4

Expert Comment

ID: 37729176
Could You please clarify the stucture of Your input file (which is called "output.txt")?

Sometimes there are 4 columns there, and later columns have 5 columns. Which exactly fields should be analyzed?
0

LVL 4

Accepted Solution

bazika earned 500 total points
ID: 37729248
Here is the example of shell script.
I suppose, that the first field in output.txt is "YYYYMMDD", so selecting "substr(\$1, 1, 6 )" gives us "YYYYMM" (year+month).

Also, the summary of all fields from the 3-rd is taken (i.e. field3+field4+field5 ...)

I do not know, which awk version is used, therefor, I do additional initialization of the arrays.

#!/bin/ksh

cat output.txt | awk '
\$3 != "" { cur_mon = substr(\$1, 1, 6 ) ;
if( a_sum[cur_mon] == "" ) { a_sum[cur_mon] = 0 ; a_cou[cur_mon]  = 0 }
for(i=3;i<=NF;i++) {
a_sum[cur_mon] += \$i;
a_cou[cur_mon] ++ ;
}
}
END {
for (cur_mon in a_sum )
{ printf "%s %.2f\n", cur_mon, a_sum[cur_mon]/a_cou[cur_mon] ; }
}
' | sort -k 1
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
What do responsible coders do? They don't take detrimental shortcuts. They do take reasonable security precautions, create important automation, implement sufficient logging, fix things they break, and care about users.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
###### Suggested Courses
Course of the Month10 days, 7 hours left to enroll