5 UNIX / Linux head Command Examples

by bala

What is head?
5 head examples
Syntax and Options
Related Commands

What is head?

Head prints the first N number of data of the given input. By default, it prints first 10 lines of each given file.


5 head Examples

1. Print the first N number of lines

To view the first N number of lines, pass the file name as an argument with -n option as shown below.

$ head -n 5 flavours.txt 
Ubuntu
Debian
Redhat
Gentoo
Fedora core

Note: When you simply pass the file name as an argument to head, it prints out the first 10 lines of the file.

2. Print N number of lines by specifying N with -

You don’t even need to pass the -n option as an argument, simply specify the N number of lines followed by ‘-’ as shown below.

$ head -4 flavours.txt
Ubuntu
Debian
Redhat
Gentoo

3. Print all but not the last N lines

By placing ‘-’ in front of the number with -n option, it prints all the lines of each file but not the last N lines as shown below,

$ head -n -5 flavours.txt 
Ubuntu

4. Print the N number of bytes

You can use the -c option to print the N number of bytes from the initial part of file.

$ head -c 5 flavours.txt
Ubuntu

Note : As like -n option, here also you can pass ‘-’ in front of number to print all bytes but not the last N bytes.

5. Passing Output of Other command to Head Input

You may pass the output of other commands to the head command via pipe as shown below,

$ ls | head
bin
boot
cdrom
dev
etc
home
initrd.img
lib
lost+found
media

Syntax and Options

head [OPTIONS]… [FILE]…

Short Option Long Option Option Description
-c –bytes to print N bytes from each input file.
-n –lines to print N lines from each input file.
-q –silent, –quiet Prevent printing of header information that contains file name
-v –verbose to print header information always.


Related Commands

tail

Comments on this entry are closed.

{ 1 trackback }

Previous post:

Next post: