How to use less and cat to view file contents in Linux

This article explains how to use the less and cat commands to view file contents in Linux. You will learn how to scroll through files, search for text within files, and exit the less and cat commands.

less and cat

  • cat: dump one or more files to STDOUT
    • Multiple files are concatenated together
  • less: view file or STDIN one page at a time
    • Useful commands while viewing:
      • /text searches for test
      • n/N jumps to the next/previous match
      • v opens the file in a text editor (vi by default)
    • less is the pager used by man

Dumping files with cat

cat opens the files given as its arguments and displays their contents to the terminal.

To see how cat works, try running cat /etc/profile

Unless you can read very fast, you probably noticed a problem with the output scrolling off the top of the page too quickly. cat is most useful for viewing short files; other commands, such as less, are more suited to viewing larger files.

If you dump the content of a binary file with cat to a terminal, you will make it unusable. You can use reset to clean up your garbled terminal and go on with it. When you type reset, it won’t be correctly echo-ed. It may also take a couple of seconds before your terminal is reset.

Some useful options to use with cat:

-A Show all characters, including control characters and non-printing characters
-s “Squeeze” multiple adjacent blank lines into a single blank line
-b Number each (non-blank) line of output

Navigating text with less:

Space moves ahead one full screen
b moves back one full screen
Enter moves ahead one line
k moves back one line
g moves to the top of the file
G moves to the bottom of the file
/text searches for text
n repeats the last search
N repeats last search, but in the opposite direction
q quits
v opens the file in (vi by default)

Leave a Comment