Razine
Infrastructure System Engineer

How to use head command

Introduction

Head : is built in command on unix systems or unix-like operating systems Like :

  • 386BSD.
  • Arch Linux.
  • AIX.
  • Android.
  • BSD NET/2.
  • Debian.
  • DragonFly BSD.
  • GNU Hurd.

Usage : used to display the top lines or bytes of the text files or the beginning of piped data.

How to use it ?

  • You can use it to display the beginning of large text file Like : systems log .
  • It can read top 10 lines by default :
head /var/log/user.log
  • Or you can specify the number of lines that you need to display it.
head -n 2  /var/log/user.log
head --lines=2  /var/log/user.log

Hint : –lines= number of lines === -n number of lines

OUTPUT:

root@unixcop:~# head --lines=2  /var/log/user.log
Sep 28 15:59:47 unixcop vmnet-natd: RTM_NEWLINK: name:eth0 index:2 flags:0x00001003
Sep 28 15:59:47 unixcop vmnet-natd: RTM_NEWLINK: name:wlan0 index:3 flags:0x00011043
root@unixcop:~# 
  • You can either display bytes from text file
  • bytes mean one character .. i will create text file with 10 char
echo "CharNum8--" > ~/bytes.txt
  • Then i will display the first 8 char using head
head -c 8 ~/bytes.txt
head --bytes=8 ~/bytes.txt

OUTPUT:

CharNum8
  • You can use head to read from many different files
  • I can use this option for comparison.
head -q unix.txt cop.txt 
head --quiet  unix.txt cop.txt
  • I can use head with option verbose to display the content of files with name of the file above
head -v unix.txt 
head --verbose unix.txt 

OUTPUT:

==> unix.txt <==
Name         Email 
Mostafa      Moo@unixcop.com

I will merge between verbose option and quiet option to clarify the usage of them

OUTPUT:

root@unixcop:~# head --quiet --verbose unix.txt cop.txt 
==> unix.txt <==
Name         Email 
Mostafa      Moo@unixcop.com

==> cop.txt <==
Name         Email 
Mostafa      Moo@unixcop.com
root@unixcop:~# 
  • I can use it with pipeline
cat /var/log/user.log | head -n 3
ls -lah /root | head -n 5
  • Here I can use head to store the result of command in text file
cat /var/log/user.log | head -n 3 > output.txt

OUTPUT:

root@unixcop:~# cat /var/log/user.log | head -n 3 > output.txt
root@unixcop:~# cat output.txt 
Sep 28 15:59:47 unixcop vmnet-natd: RTM_NEWLINK: name:eth0 index:2 flags:0x00001003
Sep 28 15:59:47 unixcop vmnet-natd: RTM_NEWLINK: name:wlan0 index:3 flags:0x00011043
Sep 28 15:59:47 unixcop vmnet-natd: RTM_NEWROUTE: index:3
root@unixcop:~# 
  • You can know the head version by typing :
head --version 
  • For more help you can use this option:
head --help 

Conclusion:

This article clarify how to use head command with practical examples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest articles

x