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:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements nl/cat/perl/awk
Est. reading time N/A
[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

Examples

The cat command syntax is:

cat -n file
cat -n /etc/hosts

The nl command syntax is:

nl file
nl /etc/hosts

Sample outputs:

     1	127.0.0.1 localhost
     2	#127.0.1.1 wks01.WAG160N wks01.nixcraft.net.in
     3	192.168.1.5	wks01
     4	# The following lines are desirable for IPv6 capable hosts
     5	::1 ip6-localhost ip6-loopback
     6	fe00::0 ip6-localnet
     7	ff00::0 ip6-mcastprefix
     8	ff02::1 ip6-allnodes
     9	ff02::2 ip6-allrouters
    10	10.10.29.72 v.b1 homerouter
    11	10.10.29.70 v.b2
    12	10.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

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 2 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
2 comments… add one
  • Lavi Mar 21, 2013 @ 12:23

    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

  • greatvedas Dec 16, 2015 @ 4:13

    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?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum