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

gawk: Can't print array in END block 2

Status
Not open for further replies.

sqwawk

Programmer
Aug 15, 2008
4
US
I am new to awk and have created a very simple script. It should read file lines into an array and print all lines in the END block. But when I test it nothing prints except the counter value:

1:: (should be something here ...)
2::
3::
4::
...

Could someone please tell me what I am doing wrong? It's probably something simple, but its making me crazy!

Code:
BEGIN {
	FS="*"
	RS="\r"
	counter=1
}
{
	arr[$counter] = $0
	counter = counter + 1
	#print arr[$NR] 
}
END {
  for (x = 1; x < counter; x++) {
    print x "::" arr[1]
  }	
}
 
print x "::" arr[[!]x[/!]]

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thanks for the reply.

Sorry that was a copy/paste error. I tried so many things. When arr[x] did not work, I tried using a hard coded index [1] to see if it changed the results and posted that by accident.

What finally worked was changing how and where I incremented the counter value. I changed this

Code:
    arr[$counter] = $0
    counter = counter + 1

to this

Code:
    arr[counter++] = $0

But I don't understand why the one works and the other does not. From what I understand they both do the same thing. Can anyone explain the difference to me?



 
$counter is the value of the field number counter, not the value of counter.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
well, the problem is in awk u don't need to add $ in front of the variable, so u just need to change ur old script to :
Code:
arr[counter] = $0
that should be works
cheers ;-)
 
$counter is the value of the field number counter, not the value of counter.

@PHV - Oh, so it has a special meaning and is not actually the value of my variable as I was thinking? Well that would explain why it didn't work. Thanks!
 
@gnsxhj,

Thanks for the response. Yes, that was one of the things I tried. But it didn't work so long as I was using a variable named "counter". Works perfectly with a variable name like "x" though :)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top