Where to start First steps track · 15 stages
Linux Labs

head — the first lines of a file

4 min Ubuntu 24.04 · GNU coreutils 9.4

The head command prints the beginning of a file or of command output — 10 lines by default, -n sets how many.

Cheat sheet

7 commands Printable version
  • head file.txt the first 10 lines
  • head -n 3 file.txt the first 3 lines
  • head -n -5 file.txt everything except the last 5 lines
  • head -c 100 file.txt the first 100 bytes
  • head -n 1 data.csv a table's header line
  • head -n 2 a.txt b.txt 2 lines of each, with names
  • ps aux --sort=-%mem | head the top of a long output

Overview

head prints the start of a file and stops. With no options it prints 10 lines; with -n N, N lines. With several names, each chunk gets a header:

text
student@ubuntu:~$ head -n 2 /etc/passwd /etc/group
==> /etc/passwd <==
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin

==> /etc/group <==
root:x:0:
daemon:x:1:

Most often head sits at the end of a pipeline and trims another command's long output: the largest files, the hungriest processes, the first matches. Its pair, tail, shows the end of a file.

Options

4

-n 3 and the short form -3 are the same. Full list — man head.

Option What it does Example
-n N Print the first N lines; -n -N prints all but the last N. head -n 3 file.txt
-c N Print the first N bytes. head -c 100 file.txt
-q Never print ==> name <== headers for several files. head -q -n 1 *.csv
-v Always print the name header, even for one file. head -v -n 3 app.conf

Nothing found. Try a shorter query.

Recipes

4

The five largest files in a directory

bash
ls -lS /var/log | head -n 6     # the total line and five files
du -ah /var/log 2>/dev/null | sort -rh | head -n 5

The processes using the most memory

bash
ps aux --sort=-%mem | head -n 6   # header and five processes

Peek at a file without opening it all

bash
head -n 20 /var/log/syslog        # what the log lines look like
head -c 64 archive.bin | od -c    # the first bytes of a binary file

Lines N to M

bash
head -n 30 app.log | tail -n 11   # lines 20–30
sed -n '20,30p' app.log           # the same with sed

Troubleshooting

4

head: cannot open 'x' for reading: No such file or directory

There's no file at that path. Check the name with ls and the current directory with pwd.

head: invalid number of lines

-n must be followed by a number: head -n 5, not head -n five or a bare head -n.

The output stops in the middle of a line

You used -c (bytes) instead of -n (lines). With -c, head cuts by bytes, even in the middle of a multibyte character.

The line you need isn't in the output

It's past the first ten. Raise -n, open the file in less, or find the line with grep: grep -n word file.

See also

  • tail — the last lines and following a log.
  • cat — the whole file.
  • less — page through a long file.
  • text-tools — sort, uniq, wc and other pipeline pieces.
  • grep — find lines by word rather than by number.
Loading…