Last Updated: April 23, 2019
·
9.601K
· lhagemann

log navigation with `less`

Ever need to read a file that is being appended to while reading it?

The first command we usually learn for following a log file is tail -f. Works great; until the line in the log we're looking for scrolls right past us and out of the buffer.

Another handy command in our tool box for reading log files is less. As a pager program less allows us to navigate around and search for strings.

less has a feature that is not well documented which allows us to follow a log file just like using tail -f, with the added benefit of file navigation and search. A file such as a web server access log, or an application debug log, is a great option to see this real-time appending in action.

$ less /var/log/foo.log

Basic navigation now is as simple as using the up/down arrows or the letters j & k. This is basic functionality, well documented in the less man pages.

Quickly jump to the end of the file

shift + g : While in the standard page view of a file jump to the end of the file

log text line
log text line
last line of log on this page
:

<shift + g>

jump to last line in the file
(END)

We're at the end of the file, but we care about what is being appended to the file right now, and all we see is the last line written to the file when we opened it.

The magic mystery command: shift + f puts us into follow mode. Now we have the same functionality as tail -f, with more power. Now we can observe the real-time content appended to the log file we're reading.

Search the File

To return to standard pager mode we use ctrl + c. In this mode we can use the search features in less:

/<search term> : searches forward in the file for <search term>; highlights located term

?<search term> : searches backward in the file for <search term>; highlights the located term

n : finds the next location of <search term> in the direction you are searching

shift + n : finds the previous location of <search term> in the opposite direction you are searching

Follow the term

After we enter search mode, whenever the term appears in the log it will be highlighted. Jumping forward and backward in the file, the term remains highlighted. Let's use that to help watch the logs for our search term while the log is being written.

A simple shift + g jumps us the end of the file, then we shift + f to follow. Now as the log is appended with real-time activity we can watch the file for our search term, it will be highlighted.

ctrl + c : cancel follow mode

shift + n : search backward in the file for our search term

1 Response
Add your response

yah man + basic knowledge of vim - helps a lot

over 1 year ago ·