100 Useful Command-Line Utilities

by Oliver; 2014

13. head, tail

Based off of An Introduction to the Command-Line (on Unix-like systems) - head and tail: head and tail print the first or last n lines of a file, where n is 10 by default. For example:
$ head myfile.txt      # print the first 10 lines of the file
$ head -1 myfile.txt   # print the first line of the file
$ head -50 myfile.txt  # print the first 50 lines of the file
$ tail myfile.txt      # print the last 10 lines of the file
$ tail -1 myfile.txt   # print the last line of the file
$ tail -50 myfile.txt  # print the last 50 lines of the file
These are great alternatives to cat, because often you don't want to spew out a giant file. You only want to peek at it to see the formatting, get a sense of how it looks, or hone in on some specific portion.

If you combine head and tail together in the same command chain, you can get a specific row of your file by row number. For example, print row 37:
$ cat -n file.txt | head -37 | tail -1  # print row 37
Another thing I like to do with head is look at multiple files simultaneously. Whereas cat concatencates files together, as in:
$ cat hello.txt
hello
hello
hello
$ cat kitty.txt 
kitty
kitty
kitty
$ cat hello.txt kitty.txt 
hello
hello
hello
kitty
kitty
kitty
head will print out the file names when it takes multiple arguments, as in:
$ head -2 hello.txt kitty.txt 
==> hello.txt <==
hello
hello

==> kitty.txt <==
kitty
kitty
which is useful if you're previewing many files. To preview all files in the current directory:
$ head *
See the last 10 lines of your bash history:
$ history | tail        # show the last 10 lines of history
See the first 10 elements in the cwd:
$ ls | head

<PREV   NEXT>