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?

- 133
3 Answers
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 towc -l
usingg|$
like above, to useless
'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).

- 72,889
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.

- 18,865
- 4
- 36
- 73
-
1Thanks, 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 -
1Since 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
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:

- 143
-
1Thanks, 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
&pattern
, piping still pipes the non-filtered content (withg|$wc -l
, that will give you the number of lines between the first occurrence ofpattern
and the end of the input) – Stéphane Chazelas Sep 02 '20 at 18:10