Linux/Unix: Cat Command Display Line Numbers

How do I use the cat command to display the line numbers for a file called myapp.c under Linux or Unix like operating systems?

You can use the cat command concatenate files and show on the screen under Linux or Unix like operating systems. The cat command also number all output lines starting with number one with the following syntax:


The syntax is:
cat -n fileNameHere
cat --number foo.c
OR use the more command/less command as filter when text can not be fitted on the screen:
cat --number foo.c | more
cat --number foo.c | less
The -b / --number-nonblank option number all nonempty output lines, starting with one and the syntax is:
cat -b fileNameHere
cat --number--nonblank filename
Finally, you suppress or remove repeated empty output lines with the -s / --squeeze-blank option:
cat -s -n fileNameHere
cat -s -n /etc/resolv.conf

Sample outputs:

     1	#
     2	# Mac OS X Notice
     3	#
     4	# This file is not used by the host name and address resolution
     5	# or the DNS query routing mechanisms used by most processes on
     6	# this Mac OS X system.
     7	#
     8	# This file is automatically generated.
     9	#
    10	search
    11	nameserver
    12	nameserver
    13	nameserver

OR (GNU only syntax)
cat --squeeze-blank -n filename

Say hello to nl command

Use the nl command number lines of files under Linux or Unix oses. The syntax is:

nl filename


Create a text file called hello.c as follows:

/* Purpose: Sample see program to print Hello world on stdout 
 * Author: SXI LLC
 * Copyright: None / Copyleft
/* our main */
int main(void){
	printf("Hello worldn");
	return 0;

Use the cat or nl command to display line numbers:

cat -n hello.c
nl hello.c

Sample outputs:

Fig.01: Displaying line numbers for hello.c using the cat and nl command.

A note about sed

To just print 3rd line use the sed command:
sed -n 3p /etc/resolv.conf
To just print 3rd and 5th line use the sed command:
sed -n -e 3p -e 5p /etc/resolv.conf
To see specific range, say show lines between 3 to 5, run:
sed -n 3,5p /etc/resolv.conf
For more information see man pages – sed(1).

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.