Commands - See more with less

05 Dec 2022

Viewing logs or other files on servers or even desktop systems can be done with the pager command less. Here is described how to enhance the interface of it, to make it more usable.

The default interface of less is pretty basic. Usually there is only the file content displayed and a short command line at the end of the screen. An example could be output by the httpd daemon of my blog:

Dec  4 13:56:09 op blog: XXX - - [04/Dec/2022:13:56:09 +0100] "GET /sitemap.xml HTTP/1.1" 404 0
Dec  4 16:35:45 op blog: XXX - - [04/Dec/2022:16:35:45 +0100] "GET /wp-login.php HTTP/1.1" 404 0
Dec  4 17:09:34 op blog: XXX - - [04/Dec/2022:17:09:34 +0100] "GET /robots.txt HTTP/1.1" 404 0
Dec  4 17:10:01 op blog: XXX - - [04/Dec/2022:17:10:01 +0100] "GET /contact.html HTTP/1.1" 200 471
Dec  4 23:38:12 op blog: XXX - - [04/Dec/2022:23:38:12 +0100] "GET / HTTP/1.1" 200 951
Dec  5 01:54:53 op blog: XXX - - [05/Dec/2022:01:54:53 +0100] "GET /contact.html HTTP/1.0" 200 801
:

This is good to get a quick glimpse of the contents of a file. Nevertheless the interface can be improved with the following command options:

less -iJNSP "?f%f .?m(%T %i of %m) .?ltlines %lt-%lb?L/%L. .byte %bB?s/%s. ?e(END) :?pB%pB\%..%t"

Where i is used to ignore case, J adds a columns for highlighting lines with tags and search results, N adds a second column with line numbers and S disables linewrapping. Scrolling vertically is then accomplished with the arrow keys. The last switch P is used to define a prompt for the last line. It equals the output from the = command inside less. More pattern options can be found on the man page. The final result would look like this:

*       120 Dec  4 13:56:09 op blog: XXX - - [04/Dec/2022:13:56:09 +0100] "GET /sitemap.xml HTTP/1.1" 404 0
*       121 Dec  4 16:35:45 op blog: XXX - - [04/Dec/2022:16:35:45 +0100] "GET /wp-login.php HTTP/1.1" 404 0
*       122 Dec  4 17:09:34 op blog: XXX - - [04/Dec/2022:17:09:34 +0100] "GET /robots.txt HTTP/1.1" 404 0
        123 Dec  4 17:10:01 op blog: XXX - - [04/Dec/2022:17:10:01 +0100] "GET /contact.html HTTP/1.1" 200 471
a       124 Dec  4 23:38:12 op blog: XXX - - [04/Dec/2022:23:38:12 +0100] "GET / HTTP/1.1" 200 951
        125 Dec  5 01:54:53 op blog: XXX - - [05/Dec/2022:01:54:53 +0100] "GET /contact.html HTTP/1.0" 200 801
/var/log/httpd_blog lines 107-132/2241 byte 11754/246637 5%

In the above resulting output we can clearly see the changes that got applied. The asterisks are added because a search with :n404 was done before. Also line 124 got tagged with the command :124ma. This is a jump mark which can be returned to with a single quote following displayed letter. Finally the customized command prompt shows relevant information about the file and the current status. The filename is always displayed and also the current position of the pager inside the file.