mercredi 23 septembre 2020

AWK issue : counting "non-matches"

I want to count the occurrences of some words in a file. Then I modify my code to additionally count how many lines did not match to any word.

For example here is my input file (test.txt):

fred
fred
fred
bob
bob
john
BILL
BILL

Here is my code:

awk '
    /fred/ { count["fred"]++ }
    /bob/ { count["bob"]++ }
    /john/ { count["john"]++ }
   END      { for (name in count) print name, "was found on", count[name], "lines." }
   ' test.txt

This works fine and gives me this output:

john was found on 1 lines.
bob was found on 2 lines.
fred was found on 3 lines.

Now I want to get a count of the lines that didn't match so I did the following code:

awk '
    found=0
    /fred/ { count["fred"]++; found=1 }
    /bob/ { count["bob"]++; found=1 }
    /john/ { count["john"]++; found=1 }
    if (found==0) { count["none"]++ }
   END      { for (name in count) print name, "was found on", count[name], "lines." }
   ' test.txt

I get an error on the if statement like this:

awk: syntax error at source line 6
 context is
        >>>  if <<<  (found==0) { count["none"]++; }
awk: bailing out at source line 8

Any ideas why this isn't working?

Aucun commentaire:

Enregistrer un commentaire