Home > Text Processing & Search > head

head: Output the beginning of a file

The head command displays the beginning of a text file (by default, the first 10 lines) to standard output. It is useful for quickly understanding the content or format of a file without viewing the entire file.

Overview

The head command is a utility that displays the 'head', or beginning, of a file. By default, it outputs the first 10 lines, but users can specify the desired number of lines or bytes to control the output quantity. It is frequently used to check the format of log files or large data files, or to process the initial part of a file in scripts. While `head` handles the beginning of a file, `tail` handles the end of a file.

Key Features

Key features of the head command include:

  • Outputs the beginning of text files.
  • Outputs the first 10 lines by default.
  • Allows specifying the number of lines (-n) or bytes (-c) to output.
  • Can take multiple files as arguments and output their content, separated by file.

Key Options

Commonly used head command options are grouped by purpose.

1) Output Options

2) Help

Generated command:

Try combining the commands.

Description:

`head` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Explore the various usage examples of the head command to learn its functionalities.

Output First 10 Lines (Default)

head /etc/passwd

Outputs the first 10 lines of the `/etc/passwd` file.

Output First 5 Lines

head -n 5 file.txt

Uses the `-n` option to output the first 5 lines of `file.txt`.

Output First 50 Bytes

head -c 50 log.txt

Uses the `-c` option to output the first 50 bytes of the `log.txt` file.

Usage with Pipe (|)

ls -l | head -n 5

Checks only the first 5 lines of the `ls -l` command's output.

Output First 3 Lines of Multiple Files

head -n 3 file1.txt file2.txt

Outputs the first 3 lines of file1.txt and file2.txt respectively. File name headers are also displayed.

Tips & Cautions

Points to note when using the head command are summarized here.

Tips

  • `head` can be used with `tail` to perform more complex tasks, such as outputting the middle part of a file. For example, `head -n 20 file.txt | tail -n 10` outputs lines 11 through 20.
  • When specifying the number of lines or bytes, simply typing a number after a hyphen, like `head -5 file.txt`, is considered the `-n` option.
  • When dealing with large files, using `head` is very efficient as it does not load the entire file into memory.

Related commands

These are commands that are functionally similar or are commonly used together.


Same category commands