Hi Guys I have a question about filling up an array
I have a file called USER_FILE.txt
it contains the following:
Real Name:Thomas A Username:THOMAS_A
Real Name:Thomas B Username:THOMAS_B
Real Name:Thomas C Username:THOMAS_C
Real Name:Thomas D Username:THOMAS_D
Real Name:Thomas E Username:THOMAS_E
I want to put this data into an array
here is what I am doing:
set -a User_array [ < USER_FILE.txt ]
however I do not believe this is working as when I run
echo ${User_array[0]}
nothing appears
Basically I need
echo ${User_array[0]}
to contain:
Real Name:Thomas A Username:THOMAS_A
echo ${User_array[1]}
to contain:
Real Name:Thomas B Username:THOMAS_B
echo ${User_array[2]}
to contain:
Real Name:Thomas C Username:THOMAS_C
typeset -i line=0
typeset -i max=0
while read buf[line]
do
(( line = line + 1 ))
done < foo
max=line # Get top of array
# print array
line=0
while (( line < max ))
do
echo "${buf[line]}"
(( line = line + 1 ))
done
c=0; while read line; do array[c]=`echo "$line"`; let c=$c+1; done < infile
echo ${array[1]}
Real Name:Thomas B Username:THOMAS_B
echo ${array[3]}
Real Name:Thomas D Username:THOMAS_D
### declare some integer variables...
typeset -i line=0
typeset -i max=0
### read data file directly into the array...
while read buf[line]
do
### increment array index by one...
(( line = line + 1 ))
### ... while reading from file 'foo'
done < foo
max=line # Get top of array
# print array
line=0
### while line index is less than maximum number of lines. . . .
while (( line < max ))
do
### print and increment array index.
echo "${buf[line]}"
(( line = line + 1 ))
done
Or to stay with my example:
Since you have the counter $c already, you can just use this to check how many elements are in the array. Due to the spaces in the elements #array will give a wrong value.
#fill the array:
c=0; while read line; do array[c]=`echo "$line"`; let c=$c+1; done < infile
#print the array elements:
x=0; while (( $x < $c )); do echo ${array[$x]}; let x=$x+1; done
Real Name:Thomas A Username:THOMAS_A
Real Name:Thomas B Username:THOMAS_B
Real Name:Thomas C Username:THOMAS_C
Real Name:Thomas D Username:THOMAS_D
Real Name:Thomas E Username:THOMAS_E