Displaying the contents of files

In this tutorial, we will look at different ways to display the contents of files. Here is a list of most popular command to display the file's contents:

CommandMeaning
cat fileDisplay the contents of file.
more fileBrowse through a text file.
less fileMore features than more.
head fileOutput the beginning (or top) portion file.
tail fileOutput the ending (or bottom) portion of file.

You can use the cat command to display the entire contents of a file. The more command will allow you to browse through a file or page through a file.

less command

The less command is like more except is has more features, less is more. When using the commands more or less, use the Space bar to advance the next page. Use the Enter key to advance once line and type q to quit viewing the file. The commands are based on the vim editor .

Commands of less

CommandAction
Page Up or bScroll back on page
Page Down or spaceScroll forward on page
Up ArrowScroll up one line
Down ArrowScroll down one line
GMove to the end of the text file
1G or gMove to the beginning of the text file
/charactersSearch forward to the next occurrence of characters
nSearch for the next occurrence of the previous search
hDisplay help screen
qQuit less

Head and Tail

By default head and tail only display 10 lines. If you want to see the last 15 lines of a file, you need to specify the -n and n is the number of lines.

$ tail -15 file.txt

Viewing files in Real Time

The cat command can be a fine way to view files that have static content. However, if you are trying to keep up with changes that are being made to a file in real time, cat is not your choice. You should use tail -f filename . You would use this to look at files that change often, for examples, log files. You may wanna start a program and look at the programe's log file to see exactly what it is doing.

Example

Suppose there is a file test.txt with the following content:

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
line 12

To look at this file with the cat command:

$ cat test.txt
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
line 12

If run head against it, you will see the top 10 lines:

$ head test.txt
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10

If you only want to see the top 2 lines, you can type:

$ head -2 test.txt
line 1
line 2

And the tail command will display the last 10 lines:

$ tail test.txt
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
line 12

To look at the last line:

$ tail -1 test.txt
line 12