1

I want to count the occurrence of a pattern per line and also get the last matching line number

So for counting patterns I would use

grep -c pattern file

and for last matching line number

grep -n pattern file | cut -d : -f 1 | tail -1

Is there any way by which I get both the results by greping only once? The file I am working with is large and I need to iterate this for several patterns, so I would like to avoid greping twice.

4

You could use awk instead of grep:

awk '/pattern/ {last = NR; count++}
     END {printf "Last: %s\nCount: %d\n", last, count}' < file

Beware that awk patterns are extended regular expressions (with slight differences with grep -E ones wrt backslash).

You could also use only one awk invocations for all your patterns:

awk '!patterns_finished{patterns[$0]; next}
     {
       for (p in patterns) if ($0 ~ p) {
         last[p] = NR
         count[p]++
       }
     }
     END {
       for (p in patterns)
         printf "%s: count=%d last=%s\n", count[p], last[p]
     }' patterns.txt patterns_finished=1 file

(assuming patterns.txt contains the list of patterns, one per line).

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.