Commands

Less Command in Linux with Examples

Less Command in Linux

The less command is a powerful terminal pager utility that every Linux user should master. Whether you’re a system administrator analyzing log files or a developer reviewing code, less provides an efficient way to view and navigate text files of any size. This comprehensive guide will explore everything from basic usage to advanced techniques, equipping you with the knowledge to leverage this versatile command effectively.

What is the Less Command?

The less command is a terminal pager program that allows you to view text files or command outputs one screen at a time. Unlike its predecessor more, the less command offers enhanced functionality including both forward and backward navigation capabilities. The name itself is a play on the Unix philosophy that “less is more,” as it provides more features while maintaining simplicity.

Core Benefits of Using Less

Less offers several advantages that make it an essential tool in your Linux arsenal:

  • Memory efficiency: It only loads portions of files as needed, allowing it to handle extremely large files with minimal resource consumption
  • Bi-directional navigation: Move both forward and backward through files with ease
  • Robust search functionality: Find specific text patterns quickly
  • Advanced features: Set bookmarks, view multiple files simultaneously, and monitor file changes in real-time
  • File examination without modification: View files without risk of accidental changes

When to Use Less

The less command proves particularly valuable in numerous scenarios:

  • Reading configuration files without editing them
  • Navigating through lengthy documentation or man pages
  • Analyzing system logs for troubleshooting
  • Reviewing command outputs that exceed one screen
  • Monitoring log files that are actively being updated

Basic Syntax and Getting Started

Command Syntax

The basic syntax for the less command follows this pattern:

less [options] filename

Where options modify less’s behavior and filename specifies the file you want to view.

Opening a File

To open a file with less, simply specify the file path:

less /etc/updatedb.conf

This displays the file contents in your terminal window. The file name appears in the bottom-left corner of your screen, helping you keep track of what you’re viewing.

Using Pipes with Less

One of less’s most powerful features is its ability to process output from other commands through pipes:

command | less

For instance, to view a directory listing that’s too large for a single screen:

ls -la | less

Or to examine detailed process information:

ps aux | less

This technique is invaluable when dealing with commands that generate extensive output.

Exiting Less

To exit less and return to your command prompt, simply press q. This keyboard shortcut works regardless of where you are in the file.

Essential Navigation Commands

Mastering navigation is crucial for effectively working with less. The following commands will help you move through files with precision and efficiency.

Basic Movement Keys

  • Moving down one line: Press Enter, j, or the down arrow
  • Moving up one line: Press k or the up arrow
  • Forward one screen: Press Space or f
  • Backward one screen: Press b
  • Forward half screen: Press d
  • Backward half screen: Press u

Jumping to Specific Positions

  • Go to the first line: Press g
  • Go to the last line: Press G
  • Move to a specific line number: Type the number followed by g (e.g., 42g to go to line 42)

Customizing Movement

You can specify exactly how many lines to move by typing a number before a movement command:

  • Move forward 5 lines: Type 5 followed by Enter
  • Move forward 10 screens: Type 10 followed by Space

Understanding the Display

As you navigate, less provides helpful indicators:

  • A colon (:) at the bottom of the screen indicates more content is available
  • When you reach the end of the file, (END) appears at the bottom
  • The status line shows the file name, position percentage, and other relevant information

These navigation techniques make less exceptionally flexible for exploring files of any size. With practice, moving through files becomes second nature, allowing you to quickly locate information without opening a full-featured text editor.

Searching in Less

The search functionality in less is one of its most powerful features, allowing you to quickly find specific information within files of any size.

Basic Search Functionality

To initiate a search:

  • Search forward: Press / followed by your search pattern, then press Enter
  • Search backward: Press ? followed by your search pattern, then press Enter

For example, to search for “error” in a log file, press / then type “error” and press Enter. Less will highlight all instances of “error” and position the display at the first match.

Navigating Search Results

After performing a search:

  • Press n to move to the next occurrence of the pattern
  • Press N to move to the previous occurrence

When using backward search (?), the functions of n and N are reversed – n finds the previous occurrence, while N finds the next one.

Case Sensitivity in Searches

By default, searches in less are case-sensitive. There are two ways to make searches case-insensitive:

  • Use the -i option when starting less: less -i filename
  • While in less, press I to toggle case sensitivity on or off

Opening Files with a Search Pattern

You can start less with a specific search pattern already applied:

less -p"searchterm" filename

This command opens the file and immediately positions the display at the first occurrence of “searchterm”.

Using Regular Expressions

Less supports basic regular expressions for more complex pattern matching:

  • . matches any single character
  • * matches zero or more occurrences of the previous character
  • ^ matches the beginning of a line
  • $ matches the end of a line

For example, to find all lines beginning with “Error:”, use the search pattern ^Error:.

Learning to use less’s search capabilities effectively can dramatically improve your efficiency when analyzing logs, code, or any text-based content.

Common Less Command Options

Less offers numerous command-line options that modify its behavior to suit your specific needs. Here are some of the most useful ones:

Displaying Line Numbers

To show line numbers in the displayed file:

less -N filename

This adds a line number at the beginning of each line, which is particularly helpful when reviewing code or when you need to reference specific lines.

Preserving Screen Content

By default, less clears the terminal when you exit. To keep the file content visible after exiting:

less -X filename

This option is valuable when you need to refer to the file content while executing other commands.

Case Insensitivity in Searches

To make searches case-insensitive by default:

less -i filename

This allows you to find text regardless of capitalization, which is often more convenient than case-sensitive searching.

Showing File Information

For a more detailed status line with percentage information:

less -m filename

For even more comprehensive information, including current line number and total lines:

less -M filename

This additional context helps you understand your position within large files.

Handling Long Lines

To prevent long lines from wrapping and instead allow horizontal scrolling:

less -S filename

Navigate horizontally using the left and right arrow keys when this option is enabled. This is particularly useful when viewing formatted data like tables or code with long lines.

Real-time File Monitoring

To watch a file for changes (similar to tail -f):

less +F filename

This is extremely valuable for monitoring log files as they’re being updated. Press Ctrl+C to stop following and return to normal browsing mode.

Setting Tab Width

To specify how many spaces a tab character should display as:

less -x4 filename

This example sets tabs to display as 4 spaces, which helps maintain proper formatting when viewing code or other tab-formatted content.

Combining Options

You can combine multiple options in a single command:

less -NiX filename

This displays the file with line numbers, case-insensitive searching, and preserves screen content upon exit.

These options make less highly customizable, allowing you to tailor its behavior to match your specific requirements for different scenarios.

Advanced Less Features

Beyond the basics, less offers advanced capabilities that can significantly enhance your productivity when working with text files.

Working with Multiple Files

Open multiple files simultaneously:

less file1.txt file2.txt file3.txt

Navigate between files using:

  • :n to move to the next file
  • :p to move to the previous file

The status line indicates which file you’re viewing (e.g., “file 1 of 3”).

Setting Bookmarks

Mark important positions within a file for quick reference:

  1. Navigate to the desired location
  2. Press m followed by a letter (a-z) to mark that position
  3. Return to a bookmark by pressing ' (apostrophe) followed by the letter you assigned

For example, press ma to set bookmark ‘a’, and later press 'a to return to that position.

Editing Files from Less

While less doesn’t support editing directly, you can open the current file in an editor:

  1. Press v while viewing a file
  2. The file opens in your default editor (usually defined by $EDITOR)
  3. After editing, you’ll return to less with the file reloaded

Customizing Less with Environment Variables

Set default options by defining the LESS environment variable:

export LESS='-N -i -S'

Add this to your .bashrc or .zshrc file to make these options permanent.

Reading from Standard Input

Less can read from standard input without explicit piping:

command | less

Saving Output to a File

Save displayed content to a file:

  1. Press s while viewing content
  2. Enter the filename when prompted
  3. The current display will be saved to that file

Using Patterns to Filter Content

Display only lines matching a pattern:

&pattern

This acts as a filter, showing only matching lines, which is useful for focusing on specific information in large files.

These advanced features make less an incredibly versatile tool that goes far beyond simple file viewing, helping you work more efficiently with text-based content.

Real-World Use Cases

The less command proves invaluable in numerous practical scenarios that Linux users encounter regularly.

Viewing and Analyzing Log Files

Log files can be enormous and difficult to navigate. Less makes this task manageable:

less /var/log/syslog

Combine with options for even better results:

less -N +G /var/log/syslog

This shows line numbers and starts at the end of the file, which is ideal for checking recent log entries.

Real-time Log Monitoring

Monitor logs as they’re being written:

less +F /var/log/messages

This behaves similarly to tail -f but with all the navigation capabilities of less when you press Ctrl+C to stop following the file.

Examining Command Output

When commands produce extensive output, pipe it to less:

dmesg | less
find / -name "*.conf" | less

This allows you to examine the output at your own pace and search for specific information.

Comparing Configuration Files

Open multiple configuration files to compare settings:

less /etc/php/7.4/php.ini /etc/php/8.0/php.ini

Use :n and :p to switch between files, making comparisons significantly easier than using separate terminals or windows.

Code Review

When reviewing code, use line numbers and search functionality:

less -N functions.php

Then search for specific functions or variables using /function_name. This makes code review more efficient, especially for large files.

System Administration Tasks

Examine system information:

cat /proc/cpuinfo | less
less /etc/passwd

In each case, less provides a controlled, navigable view of information that would otherwise be difficult to analyze.

These real-world examples demonstrate how less is not merely a file viewer but an essential tool for efficient data analysis and system management in Linux environments.

Tips and Tricks for Power Users

Take your less command skills to the next level with these advanced techniques that can dramatically improve your productivity.

Creating Aliases for Common Options

Create shortcuts for frequently used less configurations:

alias lless='less -N -S -i'

Add this to your .bashrc file to make it permanent. This creates a custom command that automatically includes line numbers, horizontal scrolling, and case-insensitive searching.

Combining Less with Grep for Highlighted Searches

Use grep to highlight patterns before viewing with less:

grep --color=always "pattern" file | less -R

The -R option preserves the color codes from grep, making search results stand out clearly.

Horizontal Scrolling for Wide Content

When viewing tables or code with long lines:

less -S filename

Use left and right arrow keys to scroll horizontally, making it easier to read content that doesn’t fit within your terminal width.

Jumping to Specific Percentages

Go to a percentage position in the file:

50p

This jumps to the 50% mark in the file, which is useful for quickly navigating large files.

Scroll Window Without Moving Cursor

To scroll the window but keep the cursor on the same line:

  • z followed by Enter: Repositions the current line to the top
  • z.: Repositions the current line to the center
  • z-: Repositions the current line to the bottom

This technique is particularly useful when you want to see more context around your current position.

Using Regular Expressions Effectively

Advanced search patterns using regular expressions can help you find specific information:

/^[0-9]{3}\.[0-9]{3}\.[0-9]{3}\.[0-9]{3}

This would search for IP address patterns, allowing you to quickly locate network-related information in log files.

Customizing Status Line Information

For a more informative experience, combine options:

less -M filename

This shows detailed file information including line numbers and percentage, helping you maintain context in large files.

Searching for Binary Data

When working with files containing binary data:

less -f filename

The -f option forces less to open binary files, which can be useful when examining mixed content.

Mastering these advanced techniques will elevate your command-line productivity and make complex file operations significantly more efficient.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button