Find the answer to your Linux question:
Results 1 to 2 of 2
Hi, I'm in dire need of some help for AWK. I'm a college student and my statistics professor decided he'd teach AWK in the last two days of our class, ...
  1. #1
    Just Joined!
    Join Date
    Jun 2007
    Posts
    1

    AWK help please - beginner

    Hi, I'm in dire need of some help for AWK. I'm a college student and my statistics professor decided he'd teach AWK in the last two days of our class, even when it's not programming class and we don't even have computers in class to experiment. Anyway, I tried looking at AWK tutorials, but it doesn't necessarily teach me in the sequence our professor taught it. This is the code our professor wrote on the board for printing lines. I can't figure the thing out. If anyone can interpret it or correct me (if I miscopied the code), thank you.

    Abe M 70
    Bea F 65
    Cathy F 67
    Dave M 69

    Code:
    {if ($2 == "M"){
    s=s+$3
    n=n+1
    }END{
    print s, n, s/n, "avg height"
    }
    I have trouble understand the "s=s+$3" and "n=n+1" lines. What do those mean? Also, I have trouble understanding the "print" line. Obviously it means to print, but what would it print? "s" "n" and "s/n?" What is the "s/n" line?

    Here's another one.

    Abe M 70
    Bea F 65
    Cathy F 67
    Dave M 69

    Code:
    {
    if ($N / [fF] /) {
    fsum = fsum + 3
    fnum = fsum + 1
    }
    if ($2N/[mM]){
    msum = msum + $3
    mnum = mnum + 1
    }
    }
    What does "if ($N / [fF] /)" or "($2N/[mM])" mean?

    THX


    I've studied HTML, Javascript and CSS in the past, and I like to know what each line or code does. I'm very OCD with programming, but it just frustrates me that the professor is simply teaching it this way WITHOUT (i repeat) a computer. This has got to be, by far, the most knuckleheaded professor I've probably taken in this college. Thx for the help.

  2. #2
    Linux User
    Join Date
    Jun 2007
    Posts
    318
    I can help you with the 1st one. In awk a line is passed as a series of parameters. So the 1st line is passed as:

    $1=Abe $2=M $3=70

    So the code does this:

    {if ($2 == "M"){
    Only process lines with the 2nd param equal to "M".

    s=s+$3
    Add the value of the 3rd parameter to variable 's'. Looks like it's height in inches.

    n=n+1
    Add 1 to variable 'n'. This is a counter.

    }END{
    Process the following (print) when the end of input os reached.

    print s, n, s/n, "avg height"
    Print the values of 's', and 'n'. The 's/n' means print the value of 's' divided by the value 'n' or, in other words, the avreage.

    }

    So the script is looking for persons whose last initial is 'M' and calculates their average height.

    Hope that helps.

    Vic

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...