user2793614
user2793614

Reputation:

Get the average of the selected cells line by line in a file?

I have a single file with the multiple columns. I want to select few and get average for selected cell in a line and output the entire average as column.

For example:

Month    Low.temp     Max.temp     Pressure      Wind       Rain 
JAN       17             36           120          5          0
FEB       10             34           110          15         3  
MAR       13             30           115          25         5
APR       14             33           105          10         4
.......

How to get average temperature (Avg.temp) and Humidity (Hum)as column?

Avg.temp = (Low.temp+Max.temp)/2

Hum = Wind * Rain

To get the Avg.temp

Month    Low.temp     Max.temp     Pressure      Wind       Rain   Avg.temp      Hum
JAN       17             36           120          5          0      26.5          0
FEB       10             34           110          15         3       22          45  
MAR       13             30           115          25         5      21.5        125
APR       14             33           105          10         4      23.5         40
.......

I don't want to do it in excel. Is there any simple shell command to do this?

Upvotes: 0

Views: 31

Answers (1)

fedorqui
fedorqui

Reputation: 289625

I would use awk like this:

awk 'NR==1 {print $0, "Avg.temp", "Hum"; next} {$(NF+1)=($2+$3)/2; $(NF+1)=$5*$6}1' file

or:

awk 'NR==1 {print $0, "Avg.temp", "Hum"; next} {print $0, ($2+$3)/2, $5*$6}' file

This consists in doing the calculations and appending them to the original values.

Let's see it in action, piping to column -t for a nice output:

$ awk 'NR==1 {print $0, "Avg.temp", "Hum"; next} {$(NF+1)=($2+$3)/2; $(NF+1)=$5*$6}1' file | column -t
Month  Low.temp  Max.temp  Pressure  Wind  Rain  Avg.temp  Hum
JAN    17        36        120       5     0     26.5      0
FEB    10        34        110       15    3     22        45
MAR    13        30        115       25    5     21.5      125
APR    14        33        105       10    4     23.5      40

Upvotes: 2

Related Questions