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!

Awk while loop question

Status
Not open for further replies.

intell2003

Technical User
Dec 7, 2009
3
US
Hello, new to the site and I'm looking for help. I'm doing an Awk tutorial to try and get used to it for recreative use. I found a tutorial that I have been going through until I came across this one particular problem.

Write an awk program to print out the total number of computers held by the organization using the data file awktext3. Use a while statement to perform this.
The awktext3 file stated above contains the following information:

Management 22 Electronics 46 Engineering 12
Health_Science 5 Tourism 20 Registry 18
Computing_Centre 300 Library 4 Halls 2
 
Let's see your code so far... which part are you stuck with?

(There's no point in doing a tutorial if we just give you the solution :) )

Annihilannic.
 
I have tried a few things for this problem, the latest being:
{ field = $2
while ( field <= NF )
{
tot += field;
field += 2
}}
END { printf("$d\n", tot) }

It is printing out $d for output. I have tried other scripts but have overwritten them with current attempt. Apologies for not putting this down in the first post, I meant to. Also, thank you for your response and possible future help.
 
Good start... $2 refers to the contents of field 2, not the number 2. So you want to use just 2 initially.

Then when you add to the total, you are interested in the contents, so you should change that one to $2.

Finally, printf() format specifiers are prefixed by % symbols, not $.

Annihilannic.
 
Sorry, typo, that should read:

Then when you add to the total, you are interested in the contents, so you should change that one to $field.


Annihilannic.
 
Thank you very much for the help. Some of the suggestions you gave made me want to smack myself in the head because I overlooked them. Thank you again for the help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top