Less command is a Linux utility that can be used to read the contents of a text file one page (one screen) at a time. It has faster access because if a file is large, it doesn’t access the complete file, but accesses it page by page.
For example, if it’s a large file and you are reading it using any text editor, then the complete file will be loaded to the main memory. The less command doesn’t load the entire file but loads it part by part which makes it faster.
Syntax of `less` command in Linux
The basic syntax of the less command is as follows:
less [options] filename
Here, `filename` represents the name of the file we want to view using the `less` command.
Using Less with Pipelines
The less command can also be used in conjunction with other commands through pipelines. This allows us to view the output of a command directly in the less pager.
Note: I’m using dmesg output as input to less command in the following examples.
For Example: If you want to read the contents of dmesg command, it’s better to use it with fewer command
dmesg | less
Output:
Commonly Used Option in `less` command.
The less command provides several options that modify its behavior. Here are some commonly used options:
|
Automatically exit when reaching the end of the file. |
Force non-regular files to be opened. |
Exit if the entire file can be displayed on the first screen. |
Highlight the string that was found by the last search command. |
Suppress highlighting of search matches. |
Ignore cases when searching. |
Suppress line numbers. |
Start at the first occurrence of the specified pattern in the file. |
Squeeze consecutive blank lines into a single line. |
We can combine these options to customize the behavior of the less command according to our needs.
Example Usage of `less` command in Linux
Let’s look at a few examples to illustrate the usage of the less command with different options.
Searching for a pattern
dmesg | less -p "fail"
The above command tells less to start at first occurrence of pattern “fail” in the file and displaying the file from that point.
Output:
Displaying line number
dmesg | less -N
The -N
option displays line numbers along with the file content, allowing you to reference specific lines easily.
Output:
Checking a small file
less -F /home/Mandeep/test/first.erl
In this example, the file `/home//Mandeep/test/first.erl` is small enough to fit on a single screen. The `-F` option causes less to exit immediately without displaying the file since it can be fully shown in one go.
Conclusion
In this article we have discussed `less` command which allows users to read large text files efficiently by loading and displaying them incrementally. We can say that by utilizing less with pipelines, users can also directly view the output of other commands, enhancing its usefulness. Overall, less command is a valuable tool for managing and exploring the contents of text files in Linux.