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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Automatically writing each line to an array in ksh

Status
Not open for further replies.

warburp

IS-IT--Management
Oct 27, 2003
44
GB
Hi

Hopefully someone can help. I have a file with values written to by a number of other scripts and I wan to be able to automatically add each line in the file to a separate array value. I have tried the following but it does not work:

cat $DIRTEMP$PIDFILE | while read LINE #read each line in the file
set -A array # null out previous arrays

do
arr[$ARR] = $LINE
echo $LINE
echo ${arr[$ARR]}
$ARR = $ARR + 1
done

Any one suggest how this can be done.

Thanks

Phil.

 
didn't try your script, but there should be
ARR=$ARR+1

tikual
 
tikual,
Code:
ARR=1
ARR=$ARR+1
ARR becomes "1+1"

I think it should be:

Code:
ARR=`expr $ARR + 1` # watch the spaces !!!

or

Code:
ARR=$(($ARR+1)) # ksh

summary:
Code:
ARR=0
set -A array           # Move it BEFORE the while
cat $DIRTEMP$PIDFILE | while read LINE
do
    arr[$ARR]=$LINE    # NO spaces 
    echo $LINE
    echo ${arr[$ARR]}
    ARR=$(($ARR+1))
done
 
Try this ...

#!/usr/bin/ksh
#
# Read file $FILE in $array[*]
#

set -A array
typeset -i array_index=0
while read array[$((array_index+=1))] ; do
:
done < $0

#
# Print array
#

typeset -i index=0
while (( $((index+=1)) < ${#array[*]} )) ; do
printf &quot;[%3d] %s\n&quot; $index &quot;${array[$index]}&quot;
done


Jean Pierre.
 
sorry, you must read

done < $FILE

Jean Pierre.
 
If your file only has a single value per line, then you could use the following to load the array (no loop required)...

set -A arr $(<infile)
 
You can try something like this in ksh:
Code:
eval $(awk '{
printf &quot;arr[%d]=\&quot;%s\&quot;\n&quot;,NR,$0
}' $DIRTEMP$PIDFILE

Hope This Help
PH.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top