Skip to content

less Command: A Powerful File Viewer

Summary

The less command is a powerful and versatile file viewer that allows you to navigate through files one screen at a time, providing efficient and flexible viewing capabilities.

Introduction

less is a terminal-based program used to view the contents of text files. It is similar to more, but has more advanced features that allow you to move both forward and backward in the file. Unlike editors like vi or nano, less is a read-only viewer, meaning you can't accidentally modify the file. This makes it a safe and convenient tool for examining large files without loading the entire file into memory.

Use Case and Examples

Viewing a File

less my_large_file.txt
This command opens my_large_file.txt in less. You can then use the arrow keys to scroll through the file. Press q to quit.

Searching for a Pattern

less my_large_file.txt
/pattern
Once the file is open in less, type / followed by the pattern you want to search for, and press Enter. less will highlight the first occurrence of the pattern. Use n to go to the next match and N to go to the previous match.

Navigating to a Specific Line

less +100 my_large_file.txt
This command opens my_large_file.txt in less, starting at line 100.

Piping Output to less

dmesg | less
This command pipes the output of the dmesg command to less, allowing you to view system messages one screen at a time. This is especially useful for long outputs that would otherwise scroll off the terminal screen.

Viewing Multiple Files

less file1.txt file2.txt file3.txt
This command opens multiple files in less. You can switch between files using :n (next file) and :p (previous file).

Commonly used flags

Flag Description Example
-N Displays line numbers. less -N my_file.txt
-S Chops long lines instead of wrapping them (useful for log files). less -S my_file.log
-i Ignores case distinctions in searches. less -i my_file.txt
-g Only highlights the current match, not all matches during search. less -g my_file.txt
+F Follow mode. Similar to tail -f, it displays the file and updates the view as new content is added. Press Ctrl+C to exit follow mode. less +F my_log_file.log
-p pattern Starts less at the first occurrence of the specified pattern. less -p "error" my_log_file.log
-Q Suppresses the "Press q to quit" prompt. less -Q my_file.txt
-x n Sets tab stops every n spaces. Useful for files with inconsistent tab spacing. less -x 8 my_file.txt


Share on Share on

Comments