The less command is great for viewing the contents of a text file in the terminal without cluttering the screen.
If you’re viewing a large file and looking for specific text in it, you don’t have to do it manually.
You can search in the less command.
Now I will show you how to do it.
Search when using the less command
Open the file for viewing with the less command.
Then press the / key followed by the pattern you want to search for and press the Enter key.
It will search forward from your current location and move you to the first match it finds. Matched parts are highlighted.
For example, enter /scanner:
- The transition to the next matched sample is carried out by pressing the n key.
- You can return to the previous match by pressing the N key (shift+n).
You can also move up and down the page using the spacebar and b.
Found parts, if any, are highlighted.
If the sample you are looking for is not found, a message will appear below “Pattern not found (press RETURN)”.
You can search backwards using ?pattern instead of /pattern. This will start the search in the opposite direction from the current location.
Let’s do a case-insensitive search in less
By default, searches in less are case sensitive.
To run a case-insensitive search, you can type the following in the less view:
You can use it before starting a search or during a search.
It works the same way.
Actually, this toggles the search case-sensitive.
Press it again and the search will again be case sensitive.
You can also use i instead of I, however i will not do a case-insensitive search if the searched pattern has an uppercase letter.
Therefore, it is better to use I here.
If you want, you can start the search case-insensitively from the beginning:
less -I filename
You can do an inverse search with /!pattern and look for lines that don’t match the pattern.
How to show only matching lines
Don’t feel like pressing n or N to see matching patterns?
You can only show matching lines by searching with &pattern instead of /pattern.
Let’s also introduce scanner:
You can use the arrow key to move through the lines.
If you look at the bottom, you will notice that the line numbers are displayed there, and they are not consecutive, as you only see matching lines.
How to start a search with the less command
You can start searching for a term immediately after opening a file with the less command.
You can perform a case-insensitive search by adding the -I option, as shown below:
less -Ip pattern filename
Note that the order of the options matters here.
The above command will not work if you use -pI.
Because less is just a viewer, you can’t do find-and-replace like you can in Vim.
less has some other search capabilities when browsing content.
You can read the man page for more details.
In my opinion, searching in less while viewing a file is fine.
However, for serious searching in the text of a file, it is better to use the grep command.
#search #command #good