shary
February 6, 2007, 2:21pm
1
hello experts
can u tell me please how i have a text file .
In third field of a file there are names like
abb
asa
asas
asasas
i just want to store the third filed of a file in an array.
and to display the result in a same order using for loop through array
can any one tell me how to do this in the shell script
take care bye
shary
What is the field delimiter? The following assumes a comma:
integer i=0
awk 'BEGIN {FS=OFS=","} {print $3}' file.txt | while read item; do
myarray[$i]=$item
i=$i+1
done
If the fields are delimited by spaces, just eliminate the BEGIN block:
integer i=0
awk '{print $3}' file.txt | while read item; do
myarray[$i]=$item
i=$i+1
done
You can loop through the array you created with this:
for x in ${myarray[*]}; do
print $x
done
With bash:
$ cat file
filed1 filed2 field3_1 field4
filed1 filed2 field3_2 field4
filed1 filed2 field3_3 field4
filed1 filed2 field3_4 field4
filed1 filed2 field3_5 field4
filed1 filed2 field3_6 field4
filed1 filed2 field3_7 field4
$ a=($(cut -d" " -f3 file))
$ i=0;until((i>=(${#a}-1)));do echo ${a};((i+=1));done
field3_1
field3_2
field3_3
field3_4
field3_5
field3_6
field3_7
With awk:
awk '{x[NR]=$3}
END{for(i=1;i<=NR;i++)print x}' file
This will work with ksh93 also.
anbu23
February 7, 2007, 2:15am
6
eval ` awk ' { printf("arr[%d]=%s\n",NR,$3) } END { printf("tot=%d",NR) }' file `
i=1
while [[ $i -le $tot ]]
do
echo ${arr[$i]}
(( i=i+1 ))
done
shary
February 7, 2007, 3:39am
7
hi experts
thank you so much for your cooperation i really appreciate your quick response.
Regards,
Shary