less can do even more

After writing my last post I took my own advice and reread the less(1) manpage. Surprisingly I found some new really handy tricks that were very helpful not even an hour later!

First of all, the pair matching. If the topmost displayed line (that’s the important part!) contains an opening bracket {, we can press this very key to find the matching closing bracket (}). It is displayed by placing the line with the matching } at the bottom. Similarly now we can press } to find the matching { to the closing bracket in the bottom line, and it gets shown as the topmost line. At first it feels strange and confusing but it makes sense after trying it out. I used {} in my example but the same “trick” works for () and []. We can also match a custom pair (sadly, only single-character) by pressing ctrl+alt+f followed by the opening character and then the closing character, to go to the closing character and ctrl+alt+b followed by the same thing to go back to the opening character. So even though there is no key for matching <> we can use ctrl+alt+f < > to match them.

I mentioned I found it useful in real life. It was when browsing logs that contained a JSON-like structured data. When coding I usually run my tests with ./test-suite |& less, so using the stuff built into less was much simpler than opening the same log in a “real text editor”. Nota bene, I could have easily done so by typing g|$vim - to go back to the top of the log file (g) and pipe (|) everything up to the end of the viewed text ($) with vim (vim - to make vim read its stdin). I could have omitted g and replaced $ with . to pipe just the visible portion of the log into vim if that’s the only part I needed at this time.

I also find the search (/) flags useful often, for example /^R treats the query as a plain text, with no regular expressions, while /^K only highlights the matches without changing the current position in file. I’ll leave learning the rest of the flags as an exercise to the reader.

blogroll

social