-1

Say I'm using a command like tail -f ./somefile as input into my awk command. And I want to continually sum a count of matches using awk, almost like running a | wc -l at the end of a command, but where it would continue receiving the input...when AWK sums the input it displays it with the END{} part of the command but since it's still receiving input, the END{} part of the command never runs...so how do I get awk to keep receiving input as it comes from the tail -f ./somefile command? Is there a looping mechanism for this I could use in the awk code segment instead of using END{}?

  • 3
    Can’t you move your processing from the END block to a record pattern block? – Stephen Kitt Sep 24 '19 at 23:39
  • +1 ... at its simplest, just removing the END pattern so your {...} is evaluated for every line... if you want to get fancy, use modulo arithmetic like !(NR%n) to evaluate every nth line – steeldriver Sep 24 '19 at 23:57
  • @StephenKitt Forgive me, I’m a bit new to awk, the record processing block it the middle one with no label? – leeand00 Sep 25 '19 at 0:53
0

You did not mention how exactly "matches" are being made, so I'm going to assume a line that matches /pattern/ {} rules would increase a count...

And I want to continually sum a count of matches using awk, almost like running a | wc -l at the end of a command

If the input is endless, I guess you would like to display the count every time it was incremented?

Basically, don't use END {} rule in this case; just print the counter out where you incremented it; like this example AWK program:

# Initializer
BEGIN {
    counter=0;
}

# Pattern A
/^COUNT$/ {
    ++counter;
    print counter;
}

# Pattern B
/^HERE$/ {
    ++counter;
    print counter;
}

This program will count (and display the counter value) every time a line COUNT or HERE appear in the input.

If you have a lot of patterns to match and would like to minimize code repetition, you can use AWK function to combine count and display into one operation:

# Initializer
BEGIN { counter=0; }

# Count and Display Function
function count() {
    ++counter;
    print counter;
}

# Pattern A
/^COUNT$/ { count(); }

# Pattern B
/^HERE$/ { count(); }

Screenshot (both programs above give identical output):

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.