Saideep Pavuluri
Saideep Pavuluri

Reputation: 102

Find average of numbers from a specific line

I have a text file with 2 columns of numbers.

10 2
20 3
30 4
40 5 
50 6
60 7 
70 8 
80 9
90 10
100 11
110 12
120 13
130 14

I would like to find the average of the 2nd column data from the 6th line. That is ( (7+8+9+10+11+12+13+14)/8 = 10.5 )

I could find this post Scripts for computing the average of a list of numbers in a data file and used the following:

awk'{s+=$2}END{print "ave:",s/NR}' fileName

but I get an average of entire second column data.

Any hint here.

Upvotes: 2

Views: 569

Answers (2)

sjsam
sjsam

Reputation: 21965

Below script should do the job

awk 'NR>=6{avg+=$2}END{printf "Average of field 2 starting from 6th line %.1f\n",avg/(NR-5)}' file

Output

Average of field 2 starting from 6th line 10.5

Upvotes: 0

ghoti
ghoti

Reputation: 46846

This one-liner should do:

awk -v s=6 'NR<s{next} {c++; t+=$2} END{printf "%.2f (%d samples)\n", t/c, c}' file

This awk script has three pattern/action pairs. The first is responsible for skipping the first s lines. The second executes on every line (from s onwards); it increments a counter and adds column 2 to a running total. The third runs after all data have been processed, and prints your results.

Upvotes: 2

Related Questions