Terminal 101: Head and Tail Text Commands
Posted 07/23/2012 at 10:00am
| by Cory Bohon
Every Monday, we'll show you how to do something new and simple with Apple's built-in command line application. You don't need any fancy software, or a knowledge of coding to do any of these. All you need is a keyboard to type 'em out!
In OS X, you can easily view the contents of almost any file in the Finder by using Quick Look. But, did you know you can also do the same with the command line. The head and tail commands let you preview the first or last bits of a text file you’re working with, letting you narrow down the file that you need without opening it in a text editor like nano.
Head

The head command lets you view the first part of a text file. Use the following syntax to print out the beginning of the file to the terminal window:
head file
Replace “file” with the name of the file that you wish to view. By default, you will see the first 10 lines of the file.
Tail

The tail command lets you view the last part of a text file. Use the following syntax to print out the ending of the file to the terminal window:
tail file
Replace “file” with the name of the file that you wish to view. By default, you will see the last 10 lines of the file.
Controlling How Many Lines
With either of the commands, you’ll see only ten lines of either the beginning or end the file. You can change this to see more, or less of the file using either the head or the tail command.
To do this, you’ll use the “-n” modifier, like this:
head -n x file
Replace the “x” with the number of lines of the file you’d like to see; and, as before, replace “file” with the name of the file that you wish to preview.

So, if you wanted to view the last 5 lines of a file named “file.txt,” you’d type the following command:
tail -n 5 file.txt
Cory Bohon is a freelance technology writer, indie Mac and iOS developer, and amateur photographer. Follow this article's author, Cory Bohon on Twitter.