How to use Linux Head Command.

How To Use Linux Head Command.

This article explains how to use the Linux head utility through practical examples and detailed explanations of the most common command options.

The head command prints the first lines (10 lines by default) of one or more files or piped data to standard output.

 

Head Command Syntax

The syntax for the head command is as follows:

head [OPTION]... [FILE]...

 

  • OPTIONhead options . We will go over the most common options in the next sections.

  • FILE – Zero or more input file names. If no FILE is specified, or when FILE is , head will read the standard input.

 

How to Use the head Command

In its simplest form, when used without any option, the head command displays the first ten lines.

head filename.txt

 

Display a Specific Number of Lines

Use the -n (–lines) option followed by an integer specifying the number of lines to be shown:

head -n <NUMBER> filename.txt

You can omit the letter n and use just the hyphen () and the number (with no space between them).

To display the first 30 lines of a file named filename.txt you would type:

head -n 30 filename.txt

The following will produce the same result as the above commands:

head -30 filename.txt

 

Display a Specific Number of Bytes

The -c (–bytes) option allows to print a specific number of bytes:

head -c <NUMBER> filename.txt

For example, to display the first 100 bytes of data from the file named filename.txt you would type:

head -c 100 filename.txt

You can also use a multiplier suffix after the number to specify the number of bytes to be shown. b multiplies it by 512, kB multiplies it by 1000, K multiplies it by 1024, MB multiplies it by 1000000, M multiplies it by 1048576, and so on.

The following command will display the first five kilobytes (2048) of the file filename.txt:

head -c 5k filename.txt

 

Display Multiple Files

If multiple files are provided as input to the head command, it will display the first ten lines from each provided file.

head filename1.txt filename2.txt

You can use the same options as when displaying a single file.

This example shows the first 20 lines of the files filename1.txt and filename2.txt:

head -n 20 filename1.txt filename2.txt

When more than one file is used, each file content is preceded with a header showing the file name.

 

Use head with Other Commands

The head command can be used in combination with other commands by redirecting the standard output from/to other utilities using pipes.

The following command will hash the $RANDOM environment variable , display the first 32 bytes and display 24 characters random string:

echo $RANDOM | sha512sum | head -c 24 ; echo

 

Conclusion

By now you should have a good understanding of how to use the Linux head command. It is complementary to the tail command which prints the last lines of a file to the to the terminal.