Content From The Beginning of a File Using Head


You’ve seen how to view the contents of a file with the cat command, though, sometimes you just need to peak inside a text file. If you are looking to explore the end of the text file, then you would use the tail command.

This article makes use of a collection of random files. These files were put together to help you “Tweak Your Terminal”. Checkout our guide to setting up the random files.

With the head command you can do just that.

head [-n count | -c bytes] [file ...]

You can use it without -n or -c option and it will default to 10 lines (-n 10).
Though you are more likely to want to specify how many lines you want head to return.

head -n 1 lorem.txt
Parturient nisi. Tellus. Quam penatibus aliquet vulputate vitae, Nulla in

Specifying the total number of lines is a good way for most text files.

However, that only works because head is counting the number of new lines in the file.

What happens if there are no newlines in the text file?
Head will effectively turn into cat and output the whole file to the terminal.

This can be problematic when you are looking at a file that contains gigabytes of text.

You can tell head to count in bytes, rather than new lines.  The -c option will specify how many bytes you would like for the file.

head -c 40 lorem.txt
Parturient nisi. Tellus. Quam penatibus %
Note: a Byte is typically a single character.
However there are characters that are made up of 2 or more bytes.
For example, an emoji is made up of 4 bytes.

echo "😎👍🏻" | head -c 4
😎

When using head, you can either supply -n or -c, but it doesn’t make sense to include both.
If fact, head won’t let you supply both values.

head -n 1 -c 1 lorem.txt
head: can't combine line and byte counts

If you did want to limit the output to both bytes and lines, then you could pipe head into head.

head -n 5 decamerone.txt | head -c 100
Di vita, quali noi che furono al alcuno sé cominciamento, carissime giudice,
porgere e le spezial c

Daniel

Whilst building web applications, Daniel also sets up web servers from scratch because he has yet to find the perfect hosting solution. His philosophy is “Why settle, when you can build it better yourself?”

Recent Posts