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

Reading each number in array 2

Status
Not open for further replies.

frangac

Technical User
Feb 8, 2004
163
ZA
Hi All,

How can I do the following

number = 0123456789

By using the for loop

for (i=0;i<=length($1);++i)
{
assign each number to an arr
} ' $1

and the result

arr1=0
arr1=1
arr1=2
arr1=3
arr1=4
arr1=5
arr1=6
arr1=7
etc...

Many Thanks
Chris





 
Hi Feherke,

Thanks for your input but I dont get the results

File
====
0123456789 2006/06/06

awk '{ len=length=$1
dim=split($1,arr,"")
for (i=1;i<=dim && i < len;i++)
print i,":",arr
}' File

Output should look like this
arr0=0
arr1=1
arr2=2
etc..


What am I doing wrong????

Many Thanks
Chris
 
Hi

Sorry, I did not understand you completely, so my first code was mostly a sample. I hope this is a solution :
Code:
awk '{dim=split($1,a,""); for (i=1;i<=dim;i++) print "arr" i "=" a[i]}' File

Feherke.
 
A starting point:
awk '{
for(i=1;i<=length($1);++i)a=substr($1,i,1)
# some code here
for(j=1;j in a;++j)print "a"j"="a[j]
}' File

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Hi PHV,Feherke

Thanks.

PHV's solution is perfect (as always, right).

Feherke
Your solution does work but does not assign to each array.

Many Thanks
Chris
 
Hi

Chris said:
Your solution does work but does not assign to each array.
Then is clear : I did not understand you.

For single line input the output of PHV's and my code is similar. For multiple line input I thought my code is better :
Code:
[blue]master #[/blue] cat File
0123456789 2006/06/06
hello world

[blue]master #[/blue] awk PHV.awk File
a1=0
a2=1
a3=2
a4=3
a5=4
a6=5
a7=6
a8=7
a9=8
a10=9
a1=h
a2=e
a3=l
a4=l
a5=o
a6=5
a7=6
a8=7
a9=8
a10=9

[blue]master #[/blue] awk Feherke.awk inputfile
arr1=0
arr2=1
arr3=2
arr4=3
arr5=4
arr6=5
arr7=6
arr8=7
arr9=8
arr10=9
arr1=h
arr2=e
arr3=l
arr4=l
arr5=o

Feherke.
 
feherke, which flavor of awk split each character with an empty FS ?
 
Hi

[tt]gawk[/tt] of course. Ooops, I forgot to mention.
man awk said:
If FS is the null string, then each individual character becomes a separate field.
[gray](...)[/gray]
split(s, a [, r]) [gray](...)[/gray] Splitting behaves identically to field splitting, described above.

Feherke.
 
my (old) gawk 2.15p5 don't exhibit this behaviour :-(
 
Hi

My [tt]gawk[/tt] is 3.1.1.

Strange. I would say this is an old Perl feature and if GNU decided to extend the standard [tt]awk[/tt], they could copy this feature from the begining.

Thanks for the information, PHV.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top