Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to go through a file 1 line at a time

Status
Not open for further replies.

nroberts420

Programmer
Jun 24, 2003
27
US
I'm not sure how to go to a file one line at a time so I could use data on each line to make an average. What would be the best command to use to do this, and is it possible to use a for loop to count through a file one line at a time?
 
#!/bin/ksh

while read -- line
do
set -- $line # this loads $1 $2 .. with each field in $line
do some stuff
done < MyFile

You can also get the individual fields like this

while read -- f1 f2 f3

All this assumes that the field separater in the file is white space. If not, you'll need to change IFS to the files field separater.


 
You can also consider awk (man awk)

Hope This Help
PH.
 
if file is:
Code:
hello1    1.0    2.0    3.0
hello3    4.2    3.4
hello19   9.1    2.7    4.3    3.0

you could do awk with:
Code:
awk 'BEGIN {n=0;m=0} {for (i=2;i<=NF;i++){n+=1; m+=$i}} END {printf(&quot;average %0f\n&quot;,(m/n));}' <file>

which will sum up all but the first word on each line and divide it by the number of objects.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top