Less Command in Linux with Examples

Less Command in Linux with Examples

Less is used to view the content of a file or command page by page. Less loads one page at a time therefore it is faster as compared to other editors which copies the entire file. Less command is useful for large files.

In this tutorial, we will learn to use less command in Linux. We have used Red Hat Enterprise Linux 9 distribution.

Syntax

Less command has following syntax:

Less [OPTIONS] [FILE]

Examples of less command

View the content of a file page by page

The basic example of a less command is used to view the content of a file without using any options. Suppose we want to view the content of a file sample.txt(which is located in our current directory), we will type on the terminal:

less sample.txt

View the output of some command page by page

You can view the output of a command page by page by piping the output to less command. Suppose we want to view the output of ps command page by page, we will type on the terminal:

ps aux | less

You can scroll the output downward by scrolling down key, space bar, f and Enter key. Similarly, you can move upward with scroll-up key.

The (END) shows the end of file or command output. To quit and return press the q key from the keyboard.

Search the output

You can search the output with less command. Type / and write the pattern you want to search followed by Enter key. It searches forward with /. If you want to search backward use ? followed by search pattern and Enter key.

In the below screenshot, we have searched for the keyword root.

Show line numbers

If you want the less command show line numbers with output, use -n option. The command should be formatted as follows.

less -N sample.txt

Keep the output on terminal

By default, when less command is quit the output is cleared from the terminal. If you want to keep the content on terminal, use -X as follows:

less -X sample.txt

Watch for changes in the file

+F option is used to watch the file changes. The less command should now look like:

less +F sample.txt

Conclusion

Thank you for reading my article. For help, read the manual pages of less command. Keep visiting Linux world.