Less can filter what it shows to you (a thing I recently learned)

May 28, 2021

Recently in the Fediverse, I learned that the less pager can filter the output it shows to you. I'll quote Matthias Schmidt's message:

Wow, after 25 years of Unix experience, I learned that you can filter output in #less.

Press ampersand (&) and enter a regex to show only lines matching the regex.

Press ampersand (&) and then exclamation mark (!) to apply an inverse filter.

According to the (or a) less manpage, you can use Ctrl-N instead of '!' if you want, and use Ctrl-R to make the match literal instead of a regular expression. This less feature is sufficiently old and widespread that it's in OpenBSD and NetBSD. Based on the NEWS file and less's historical releases, this was in less 429, released in April of 2009, so it should be in anything that hasn't completely stopped updating its version of less.

After learning about this less feature, it unsurprisingly turns out to be extremely useful when I'm looking at log files and similar things. If there's a lot of output, most of it isn't meaningful, and I can figure out a pattern for what I want or most of what I don't want, this will cut out most of the noise.

Before now my usual way to do this is to use less's search and let it highlight the lines I want to pay attention to. This can work out okay if there's not too much noise and it has the advantage that I can see context in case I'm missing something, but if there's lots of noise it's less than ideal (especially if the noise breaks up what I'm interested in, so I can't see enough of it in one screen).

The one thing I wish for in this Less feature is a way to re-edit your current '&' restriction, so you can refine it (for instance to add more noise or more signal). This is something I periodically wish for in searches too, but it feels more acute here, especially for an inverse match (where you don't see what your pattern already excludes). I guess the solution to this is to stash the pattern in another window before I hit return.

Update: As Greg A. Woods pointed out in a comment, you can recall and edit previous '&' commands. For me, they seem to not necessarily carry with them the state from any Ctrl-N and Ctrl-R options you may have used, just the patterns.

(I was going to say that this shows I've never fully read the less manpage, but I feel better after finding out that this feature only dates from 2009. That's a fairly long time ago by now, but not as long as I've been using less.)

Written on 28 May 2021.
« Some thoughts on having set up a personal Alertmanager instance
Go 1.17 will still support the old GOPATH mode (as well as modules) »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Fri May 28 23:23:56 2021
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.