Linux less Command
The less
command in Linux is used for viewing file contents in a paginated way, which is particularly helpful for large files that don't fit on a single screen. Unlike cat
, less
lets you scroll up and down through a file, search for text, and view portions of the content without loading the entire file into memory.
Basic Syntax
Key Features of less
- Scrolling: View content page-by-page or line-by-line.
- Searching: Find specific text patterns within the file.
- Navigation: Move through the file using keyboard commands.
Example with Output
Example 1: Viewing a File
Using less
to view a file opens it in a paginated format, allowing you to scroll through the content.
Command
Output (on-screen navigation)
Explanation:
- When you open
file.txt
withless
, only a portion of the file appears on the screen. - You can scroll down with
Enter
(line-by-line),Space
(page-by-page), or scroll up withb
. - Press
q
to quit and return to the command prompt.
Example 2: Searching for Text in a File
Within less
, you can search for specific text patterns using /
followed by the search term.
Command
Then, within less
, type:
Output
Explanation:
/word
searches for the first instance of "word" infile.txt
.- Press
n
to move to the next occurrence andN
to move to the previous one.
Example 3: Displaying Line Numbers
The -N
option displays line numbers in the less
viewer, making it easier to reference specific lines in the file.
Command
Output
Explanation:
less -N file.txt
shows line numbers on the left side of each line.- Line numbers help identify specific sections, especially in large files.
Example 4: Viewing Output from Another Command
You can pipe the output of other commands (e.g., ls -l
) to less
to view long command output more easily.
Command
Output
Explanation:
ls -l | less
shows the output of thels -l
command one page at a time.- This is useful for commands with long output, so you don’t miss any details.
Navigation Commands Within less
Once in less
, you can use various keyboard commands for navigation:
Command | Description |
---|---|
Space | Move forward one page. |
Enter | Move forward one line. |
b | Move back one page. |
/text | Search for "text" forward. |
n | Repeat the last search forward. |
N | Repeat the last search backward. |
g | Go to the beginning of the file. |
G | Go to the end of the file. |
q | Quit less and return to the shell. |
Summary of Common less
Commands
less file.txt
: View the file with scrolling capabilities.less -N file.txt
: View the file with line numbers.ls -l | less
: View the output ofls -l
with pagination.- Within
less
, use/search_term
: Search for text patterns in the file.
The less
command is an efficient, user-friendly way to navigate large files in Linux, providing fast scrolling, text searching, and various navigational tools without modifying the file content.