head


The head command filters a stream so that only the beginning of the stream is passed to stdout. This is often used to get a quick summary of the contents of a file, or to target specific lines by index in a pipeline.

The call signature is:

head {options} {path}

If path is specified, that file will be read and streamed to stdin. If path is omitted or set to -, then this command will operate on the stream that is piped or redirected to stdin.

The most common option is -n (or the --lines long option), which defines the index of the line after which content is filtered. By default the index is 10.

To demonstrate, let's work with our numbers.txt file, which contains a simple list of numbers from one through twelve:

ninja$: head numbers.txt
one
two
three
four
five
six
seven
eight
nine
ten
ninja$:  

Although this file contains 12 lines of text, only lines up to the 10th line are passed to stdout,

Now lets change the index to 3:

·
·
·
·
·
ninja$: head -n 3 numbers.txt
one
two
three
ninja$:  

The head command also allows the index to be negative, so that lines can be filtered relative to the end of the file. For example, to pass all lines except for the last 5 lines the index can be set to -5:

·
ninja$: head -n -5 numbers.txt
one
two
three
four
five
six
seven
ninja$: