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

Split string into array not working

Status
Not open for further replies.

erche

Technical User
Aug 13, 2003
15
ID

Hi,
Can someone advise me to correct this script :

a="1,2,3,4,5,6,7,8"

nawk 'BEGIN { FS="," }
{ asum=split(a,b,FS)
printf ("%d",asum)
}

the result is asum = 0.
it supposed to be returning 8.

Please help

Thanks
 
Not sure what you want to acheive - but 'a' isn't passed into the nawk part of your script
If you want to sum array 'a' contents, then :
nawk '{
split("1 2 3 4 5 6 7 8",a)
for (j1=1;j1<=8;j1++) {
asum=asum+a[j1]
}
printf(&quot;%d&quot;,asum)
}'


HTH

Dickie Bird (:)-)))
 

Oh I see,
so, for example, the a string is created like this :
a=$(nawk 'BEGIN { printf(&quot;a,b,c&quot;); for (i=1;i<100;i+3) { printf(&quot;\n%d,%d,%d&quot;,i,i+1,i+2) }
}')

so, if i have that 'a' and and i put that a on :
nawk '{
a=$(nawk 'BEGIN { printf(&quot;a,b,c&quot;); for (i=1;i<100;i+3){
printf(&quot;\n%d,%d,%d&quot;,i,i+1,i+2)
}}')
asum=split(a,b,&quot;,&quot;)
printf(&quot;%d&quot;,asum)
}'

It should be worked ?


 
If 'a' is your shell variable, then this should work
Code:
awk -v a=$a 'BEGIN { asum=split(a,b,&quot;,&quot;);print asum }'

If your awk doesn't support setting variables in this way, try
Code:
awk 'BEGIN { asum=split(&quot;'$a'&quot;,b,&quot;,&quot;);print asum }'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top