7

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?

3 Answers3

7

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).
muru
  • 72,889
  • 1
    After &pattern, piping still pipes the non-filtered content (with g|$wc -l, that will give you the number of lines between the first occurrence of pattern and the end of the input) – Stéphane Chazelas Sep 02 '20 at 18:10
  • @StéphaneChazelas oh, that's disappointing. – muru Sep 03 '20 at 01:41
7

If less is displaying a file, issue

!grep -c pattern %

"A percent sign (%) in the command is replaced by the name of the current file", as man less tells us.

Unfortunately, since less is displaying stdin when used with man, you cannot do the same when reading manual pages. Refer to muru's answer in that case.

Quasímodo
  • 18,865
  • 4
  • 36
  • 73
  • 1
    Thanks, the % bit is the one I need :) BTW, when displaying stdin input, aside from piping to another less like in @muru's answer, we can also save it first to a temporary file: s /tmp/foo then examine the file: :e /tmp/foo, then perform your trick above. Quite a few keystrokes, but problem still solved. – Budiman Snowman Sep 04 '20 at 03:46
  • 1
    Since I can only choose one answer, I chose muru's. But upvoted your answer as well, thanks. – Budiman Snowman Sep 04 '20 at 03:47
4

If you are not fixed to less, you could type:

grep MYSEARCHEXPRESSION MYFILE | wc -l

Or:

grep MYSEARCHEXPRESSION MYFILE| less -N

Then the last line has the amount of matching lines in line number.

look also:

Maik
  • 143
  • 1
    Thanks, I'm familiar with grep. Specifically asking for establishing this inside less' interactive interface. For a comparison, in emacs I can do M-x count-matches. Tricks are allowed. For example, &PAT is close. – Budiman Snowman Sep 02 '20 at 06:55