1. Home
  2. Docs
  3. Beginning UNIX on Raven
  4. Working with text files
  5. Viewing text files

Viewing text files

UNIX has a number of commands that are useful to look at the contents of text files.  We are going to use a series of commands used on text files to explore the lyrics of Don McLean’s classic American Pie to explore these commands.  The file is in your home directory.

To print the contents of a file to screen we can just use the cat (catenate) command:

cat americanpie.txt

For larger files, it can be useful to pause the display after each page of information using the more command.  Pressing the space bar advances forwards to the next page:

more americanpie.txt

Pausing after each page can be useful, but sometimes the ability to scroll through a file is what you need to do.  In an attempt at being comical, the standard command to achieve this is called less (because less is more!).  Just like the man command, you can use the up and down arrows to scroll through a file and q to exit back to the command line.

less americanpie.txt

Another two very useful commands for looking at text files are head and tail.  As the names may suggest these return a number of lines from either the top or bottom of a file.  Typical uses for these commands include looking at the bottom of any log files (either system logs or analysis logs), checking the output from any analysis or command has completed correctly and for checking the file format of a dataset.

By default head and tail return the first or last 10 lines of a file:

head americanpie.txt

tail americanpie.txt

Returning the top 10 lines is a useful default for many purposes, but sometimes you may wish to be more specific in the number of lines you return.  This can be achieved in two different ways, a formal way defining a parameter (-n) and then it’s value, the second a lazier way just using the number of lines as your flag to the command.

head –n 2 americanpie.txt

or

head –2 americanpie.txt

Summary of text viewing commands

cat Catenates and displays files
more Displays a file a page at a time
less Scroll forwards and backwards through a file
head Display the top line of a file
tail Display the bottom lines of a file