When you need to read the contents of a text file in the Linux terminal, the most common command taught to beginners is cat. For example, typing cat config.txt will instantly print the entire file to the screen.
However, cat is a dangerous tool if you don’t know the size of the file you are opening. If you try to cat a 5-Gigabyte web server log, Linux will attempt to print all 50 million lines to your terminal at once. Your screen will scroll violently for minutes, your terminal will freeze, and your computer might run out of memory and crash.
To safely read large files, you must use a “pager” program. The standard pager in modern Linux is the less command.
How the less Command Works
Unlike cat, which dumps everything at once, the less command is intelligent. It only loads exactly what can fit on your current terminal screen.
To open a massive file safely, simply type:
less server_error.log
The screen will clear, and you will be shown the very first page of the file. The file could be 100 Gigabytes large, but less will open it in milliseconds because it isn’t trying to load the whole thing into memory.
Navigating Inside the File
Once you are inside the less interface, you can navigate through the data using simple keyboard shortcuts (which are heavily inspired by the famous vim text editor):
- Down Arrow (or j): Move down one line.
- Up Arrow (or k): Move up one line.
- Spacebar: Jump forward one entire page.
- b: Jump backward one entire page.
- G (Shift+g): Jump instantly to the absolute bottom of the file.
- g: Jump instantly back to the top of the file.
Searching for Text
The most powerful feature of less is its built-in search engine, which allows you to find specific errors in massive log files instantly.
- While viewing the file in
less, type the forward-slash key:/. - At the bottom of the screen, a prompt will appear. Type the word you are looking for (e.g.,
/error 404) and press Enter. lesswill instantly jump to the first occurrence of that text and highlight it.- To find the next occurrence in the file, simply press the n key on your keyboard.
- To search backward (up the file), press Shift+n (capital N).
How to Exit
When beginners use less for the first time, they often get trapped because standard commands like Ctrl+C do not work.
To exit the file and return to your normal terminal prompt, simply press the q key (for “quit”).