How to add line numbers to a file?

Well, there are a list of commands can be used to add line numbers to a file. We will show some typical examples.

Use command cat is as this ( this is my favorite.),

cat -n /etc/hosts

The nl command is:

nl /etc/hosts

Sample outputs:

$ nl /etc/hosts
1 ##
2 # Host Database
3 #
4 # localhost is used to configure the loopback interface
5 # when the system is booting. Do not change this entry.
6 ##
7 localhost
8 broadcasthost

The less way is,

less -N /etc/hosts

The awk way is,

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

The sed way is,

sed  =  /etc/hosts  | sed 'N; s/^/     /; s/ *\(.\{6,\}\)\n/\1  /'

The perl way is,

perl -pe '$_ = "$. $_"' /etc/hosts

Now do you have a way in Python in mind? Please feel free to comment it below.

Leave a comment

Your email address will not be published. Required fields are marked *