Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

PROBLEM

I want to specifically use AWK (GAWK, MAWK, whatever) in an AWK script to sum up the values in field 9 for every record that contains "runner__.jpx" (the underscores are placeholders for two digits 0-9) in field 6 and "good" in FIELD 7.

SAMPLE FILE

Feb 14 11:33:16 ringer a[2388]: runner01.jpx good aa 3
Feb 14 11:33:32 ringer a[2388]: runner24.jpx good xx 1
Feb 14 11:33:39 ringer a[1894]: jogger02.jpx good aa 5
Feb 14 11:33:45 ringer a[2388]: runner99.jpx stop cc 1

ATTEMPT

How could I do this? I tried using an if statement, like:

BEGIN {
    sum = 0
}

{
    if (($6 == "runner"[0-9][0-9]".jpx") && ($7 == "good"))
        sum += $9
}

END {
        printf sum
}

Is there way to do this by matching strings in fields using if statements? Am I allowed to use regular expressions within the if statement? What is an alternative method to do this? Thanks.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

The following should do the job. Note that you do not need explicit ifs, just use awk's implicit pattern-action model

awk  '$6 ~ /^runner[0-9][0-9]\.jpx$/ && $7 == "good" {s += $9};
      END{print s}' input.file
share|improve this answer
    
Thanks! Can you explain what the ~ does? Also, I actually have several "if's" to run per line, so I have them in a file that I call with awk -f scriptname.awk input.file. Could I do this with the implicit structure? –  user46865 Sep 24 '13 at 2:21
    
@JonSmith, ~ does a pattern match. And the answer to your other question is yes –  1_CR Sep 24 '13 at 2:22
    
much thanks!!!!!!!!!!!!! –  user46865 Sep 24 '13 at 2:27
    
Adding to @1_CR 's comment - tilde (~) does a pattern matching against a variable - in this case $6. You can do pattern matching against the entire line without it. –  David Kohen Sep 24 '13 at 17:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.