≡ Menu

Linux / Unix: Add Line Numbers To Files

I know how to display line numbers using vim text editor. How do display line numbers in the left side for any text file under Unix or Linux operating systems?

You can use any one of the following commands to display line numbers:

[a] cat command

[b] nl command – Display each FILE to standard output (screen), with line numbers added.

[c] Gnu less command – Less is a program similar to more , but which allows backward movement in the file as well as forward movement

[d] awk command

[e] perl or python


The cat command syntax is:

cat -n file
cat -n /etc/hosts

The nl command syntax is:

nl file
nl /etc/hosts

Sample outputs:

     1127.0.0.1 localhost
     2# wks01.WAG160N wks01.nixcraft.net.in
     4# The following lines are desirable for IPv6 capable hosts
     5::1 ip6-localhost ip6-loopback
     6fe00::0 ip6-localnet
     7ff00::0 ip6-mcastprefix
     8ff02::1 ip6-allnodes
     9ff02::2 ip6-allrouters
    1010.10.29.72 v.b1 homerouter
    1110.10.29.70 v.b2
    1210.10.29.68 v.txvip1

The less command syntax is:

less -N file
less -N /etc/hosts

The awk command syntax is:

awk '{ print FNR " " $0 }' file
awk '{ print FNR " " $0 }' /etc/hosts
awk '{ print FNR "\t" $0 }' /etc/hosts

The perl syntax is:

perl -pe '$_ = "$. $_"' file
perl -pe '$_ = "$. $_"' /etc/hosts
Share this tutorial on:
{ 2 comments… add one }
  • LaviMarch 21, 2013, 12:23 pm

    Another option with in a file is using vi (or vim).
    By: set number

    Very useful when editing specific lines number.
    To cancel: set nonumber

  • greatvedasDecember 16, 2015, 4:13 am

    Hello Vivek!

    The below FNR didnt work in my environment. I am using Solaris 10.
    awk '{ print FNR " " $0 }' file

    But NR worked !
    awk '{print NR," " $0}' file

    Can you confirm if FNR is working?

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: , , ,