less – How to Count the Number of Matches in less

less

In less, is there a way or trick to quickly count the number of matches instead of pressing N repeatedly and counting the matches manually?

Best Answer

I don't think there's a direct method, but you can hack your way around. The following command will pipe everything from the first line on the screen to the end of the file to grep -c ... | less, opening a new instance of less to show the output of grep, which will be the number of lines matching the pattern:

g|$ grep -c <pattern> | less

When you quit this less, you'll be back to the first less.

Other tricks:

  • &pattern and then pipe to wc -l using g|$ like above, to use less's pattern matching
  • jump a number of matches (e.g., do 10n x times until it fails, then proceed by y single steps to get 10x+y matches).
Related Question