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:
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:
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.
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:
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
head –2 americanpie.txt
Summary of text viewing commands
||Catenates and displays files|
||Displays a file a page at a time|
||Scroll forwards and backwards through a file|
||Display the top line of a file|
||Display the bottom lines of a file|