Printing line numbers with cat and grep

Published: 29 September 2022

Note: this article is old and may contain outdated or incorrect information.

Both grep and cat can include line numbers.

With cat:

:::text
[root@mx1 ~]# cat -n /etc/hosts 
   1  # Loopback entries; do not change.
   2  # For historical reasons, localhost precedes localhost.localdomain:
   3  127.0.0.1   localhost localhost.localdomain localhost4
   4  ::1         localhost localhost.localdomain localhost6
   5  # See hosts(5) for proper format and other examples:
   6  # 192.168.1.10 foo.mydomain.org foo
   7  # 192.168.1.13 bar.mydomain.org bar

With grep:

[root@mx1 ~]# grep -n '192.168' /etc/hosts 
6:# 192.168.1.10 foo.mydomain.org foo
7:# 192.168.1.13 bar.mydomain.org bar

Tags:

  • terminal