Question about awk command

hi gurus,

I am not sure what the below commands does.

 
awk 'BEGIN {sum=0} {sum=sum+$5} END {print sum}' input_file
 

Hello ramkumar15,

Following may help you in same.

awk '
BEGIN {sum=0} ## In begining sum variable is set to 0
{sum=sum+$5}  ## Now adding $5 values each time with it's previous values so that we can get complete SUM of $5 in variable sum
END {print sum}' input_file  ## At last printing value of variable sum

Thanks,
R. Singh

awk '   # Run awk with the following script...
BEGIN {
               # variable sum is set with a value 0
               sum=0      
} 

# File reading starts from here, read line by line...

{

  # You can also use sum+=$5 it is just a shorthand/shortcut
  # What below expression does is that it first adds the value stored in variable sum to column5 value from your file,
  # and then stores the total of the two back to the variable sum

  sum=sum+$5   

} 


END{
       # After all lines have been read from all input files given to
       # this invocation of awk, run the commands in this section.

      # Finally print sum here
      print sum
}
 ' input_file  # End the script and specify the input file(s) to be processed by this
 

This is progammed utmost meticulously, which is good practice and not a bad thing in the first place. but, using some awk - features, it could be boiled down to

awk '{sum+=$5} END {print sum}' input_file

Any awk variable is allocated on first reference and defaults to zero/empty, so the BEGIN section is superfluous. The += is the addition assignment known from e.g. C .

Do not post classroom or homework problems in the main forums. Homework and coursework questions can only be posted in this forum under special homework rules.

Please review the rules, which you agreed to when you registered, if you have not already done so.

More-than-likely, posting homework in the main forums has resulting in a forum infraction. If you did not post homework, please explain the company you work for and the nature of the problem you are working on.

If you did post homework in the main forums, please review the guidelines for posting homework and repost.

Thank You.

The UNIX and Linux Forums.