Script to find the average of a given column and also for specified number of rows??

Hi friends
I have 100 files in my directory. Each file look like this..

     Temp1 Temp2 Temp3

MAS 1 2 3
MAS 4 5 6
MAS 7 8 9
Delhi 10 11 12
Delhi 13 14 15
Delhi 16 17 18
Delhi 20 21 19
Mumbai 22 46 56
Mumbai 67 34 54
..................................
.................................. so on.

I need a script which gives gives average of the column2 Temp2 for a given row(s) e.g. Delhi or MAS
I got an awk script some thing like below from this unix forum but it is giving the average of all the rows.

$ (cd awkdir ; ls | while read filename ; do awk '{sum+=$3} END { print "Average for " FILENAME " = ",sum/NR}' $filename ; done)

Can anyone please add the grep " MAS/Delhi/.... so on" command to the existing script so that I will get my desired output...

Many thanks in advance to evryone.. This is my first posting..

Hope this helps:

awk '/Delhi/ {sum+=$3; divby++} END { print "Average for " FILENAME " = ",sum/divby}' FILENAME=foo foo

For a little flexibility, you can also try this:

awk '$1==searchme {sum+=$3; divby++} END { print "Average for " FILENAME " = ",sum/divby}' FILENAME=foo searchme=Delhi foo
for filename in *
do
  printf "Average for %s = " "$filename"
  awk '/^MAS/ || /^Delhi/ { ++n; sum += $3 }
        END { print sum / n }
  ' "$filename"
done

Hi Johnson Thanks for your quick reply...
But there is one correction in my input data..
My data looks like this..

SNO Day CITY Col1 Col2 Col3 ........... So on
1 02/01/09 MAS 1 2 3
2 02/01/09 MAS 4 5 6
3 02/01/09 MAS 7 8 9
4 02/01/09 Delhi 10 11 12
5 02/01/09 Delhi 13 14 15
6 02/01/09 Delhi 16 17 18
7 02/01/09 Delhi 20 21 19
8 02/01/09 Mumbai 22 46 56
9 02/01/09 Mumbai 67 34 54
......................................................................... an so on.

I need to find the average of column 6(for example, there are around 40 columns in my files) for only the rows which contains Delhi in a given column(in this case it is col3). I hope you understand what I am asking.. It will be a great help for me if you can modified your previous script...

Hi Reddy,
Johnson's script absolutely fine :
for filename in *
do
printf "Average for %s = " "$filename"
awk '/^MAS/ || /^Delhi/ { ++n; sum += $3 }
END { print sum / n }
' "$filename"
done

For the change in your file content just change the line :
awk '/^MAS/ || /^Delhi/ { ++n; sum += $3 }with
awk '/^MAS/ || /^Delhi/ { ++n; sum += $6 } #as u need average of column 6....So that part of the code is dealing with the column number....as u should understand from the Average formula.....:slight_smile: