There are a few Linux commands available to view the content of files. The cat
command, which stands for “concatenate”, is often used to quickly view the contents of small files. The cat
command will display the entire contents of the file, hence why it is mainly recommended for smaller files where the output is limited and does not require scrolling. To view the contents of a file using the cat
command, simply type the command and use the name of the file you wish to view as the argument:
cat [OPTIONS] [FILE]
Our VM has a few small text files that you can view with the cat command. One such file is the animals.txt file. Use the following command to switch to the Documents directory:
The cat
command displays all five lines of the file above. When viewing larger files, the cat
command can result in very lengthy output that cannot be paused to scroll through. A better method of viewing long text files, is with a pager command which has a functionality that can pause and scroll through the output of the file.
Another way to view the content of files is by using the head
and tail
commands. These commands are used to view a select number of lines from the top or bottom of a file. Taking a look at a few lines of a file can sometimes be helpful to ensure that the file is the one you want to use. Another reason to preview only the first or last few lines, is because some files, such as system log files are frequently updated with new entries. Similar to the cat
command, the head
and tail
commands use the name of the file you want to view as the argument to the command:head [OPTIONS] [FILE]
tail [OPTIONS] [FILE]
To compare the output of the head and tail commands with that of the cat command, use the cat command to view the entire alpha.txt file:
In the example above, all twenty-six lines of the file will display. To filter the output and view lines from the top of the alpha.txt file, use the head
command:
Then, to view lines at the bottom of the alpha.txt file, you use the tail
command:
By examining the output of the head
and tail
commands above, you can see that the default behavior of the head
and tail
commands in this shell is to display ten lines.
The -n
option with the head
and tail
commands can be used to specify the amount of lines to display. To use the -n
option, specify the amount of lines from the file you want to display after the option and use the filename as an argument:
head -n number_of_lines filename
For example, to change the output of the head
and tail
command to view the first five lines of the alpha.txt file and View the last five lines of the alpha.txt file: