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!

Need to read a dat file sort and store in array

Status
Not open for further replies.

mantha

Programmer
May 12, 2003
1
US
I need to read a file that has no delimeters I am using the cut command to get the data out the problem is how do I read line by line and store the what I am reading in a variable or better yet an array so that I can print and add variables together to get totals.
 
I would suggest you use an awk program, and imitate the action of 'cut' by using the awk substr() function.

 
Something like this:

Code:
function incr() {
x=`expr $x + 1`
export x
}

function printStuff() {
p=0
      while test $p -lt  $x
      do
           echo "Line segment at $p: ${mystuff[$p]}"
           p=`expr $p + 1`
      done
}
     


declare -a mystuff
x=0
lineno=0

while read line 
do
   echo $line
   mystuff[$x]=`echo $line | cut -c 1-3`
   incr 
   mystuff[$x]=`echo $line | cut -c 8-10`
   incr 
   mystuff[$x]=`echo $line | cut -c 14-16`
   incr 
   lineno=`expr $lineno + 1`
   echo "At line number: $lineno"
done < $1

printStuff

It really performs very badly, BTW.
I would try an awk solution as well.
 
You could create an array using ksh...

set -A a $(cut -c10-20 file) #----or whatever

echo ${a[0]} #----first element of array &quot;a&quot;

...but awk is more powerful. To get sum total and average is simply...

cut -c10-20 file|awk '{sum+=$1} END {print &quot;Sum=&quot;, sum, &quot;Avg=&quot;, sum/NR}'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top