How to display the contents of a text file on the terminal in Linux/Ubuntu

In this short tutorial, we cover see some simple commands that will help users learn how to open a file in linux or view its contents on the command line.

Using less

This is a pager which is useful to view long files for instance:

less filename

For instance the command below will display the content of the file output_report.txt :

less output_report.txt

By passing the -F and -X switches, less can behave like cat when applied to small files but will act normally otherwise.

For instance :
less -X new_file

Using cat

cat filename

applying cat to the same file that we used above, .i.e. :

cat new_file

Using Echo

echo “$(<file_name)”

The parenthesis ( ) are used to return the value of a given expression which in this case, is the contents of file_name .

For example:

echo “$(<new_file)”

Using printf

printf “%s” “$(<filename)”

Much like the previous command, the parenthesis ( ) are used to return the value of a given expression which in this case, is the contents of file_name .

For example:

printf “%s” “$(<new_file)”

Using tail

To display the last few lines

tail file.txt

applying tail to the file output_in_html will give the following result :

tail output_in_html

which displays the last lines of the provided file.

Using head

Used to display the first few lines.

head file.txt

Applying head to the file output_in_html will give the following result :

head output_in_html

Using more

The more command enables you to display the contents of text files in a scrollable manner. The text is shown one screenful at a time. You also have the possibility to scroll forwards and backwards through the text. You can even perform a search on the text.

For example :

more output_in_html

Will show the following :

  • Space key : Used to scroll the display, .i.e. one screenful at a time
  • Enter key : Used to scroll the display one line
  • b key : Used to scroll the display backwards one screenful at a time
  • / key : Used to search the a given pattern much like in the vi/vim editor

Conclusion :

You have seen some simple utilities that allow you to display a text file on the command line. For small files, you can use the less command, or the echo command. If you know other similar tools, do not hesitate to write them in the comments section below.

amin nahdy

Amin Nahdy, an aspiring software engineer and a computer geek by nature as well as an avid Ubuntu and open source user. He is interested in information technology especially Ubuntu and Linux based ecosystem. He loves to share and disseminate knowledge to others in a transparent and responsible way.

This Post Has One Comment

  1. In Z-shell, just use the ‘<' sign like so:
    me@host% <textfile.txt

    Z-shell has a built-in less-like pager. text will be piped normally.
    me@host% <textfile.txt | cat

Leave a Reply

Close Menu