[Solved] Help understanding this code!!

Hi guys,

I am still learning awk and much apprecated to shed some light on the following: the questions asked is below!

{
	total = i = 0
	do {
		++i
		total += $i
	} while ( total <= 100 )
	print i, ":", total
}

File used:

cat test.do
45 25 60 20
10 105 50 40
33 5 9 67
108 3 5 4

Output

3 : 130
2 : 115
4 : 114
1 : 108

Two questions :

1)

$i

--> how does it reference each field individually? i am used to $1 or $2 to reference fields or $NF for instance.

2) when it does test for condition

while ( total <= 100 )

and its true; it prints out

print i, ":", total

and then it goes to the next line. but how? where in the code that say that does that?

sorry if these seemed to be silly but i rather understand and ask than not to :slight_smile:

awk code consists of a begin, end and middle section. The middle section is executed per record or line and so there is an implicit loop. Any section can be omitted. The section you posted is from the middle section, and so is excuted by line. $i means evalute i and use the field that corresponds to that number, for example if i = 2 then $i means $2

1 Like

Thank you!!!