Bash Shell script list file content along line numbers

How can I display line numbers of a file. This can be achieved in Linux and Unix using many commands such as cat, nl, sed etc. In this post we will see how to write a script to display line numbers as well as with commands


Example1: Display line numbers using cat

cat -n filename.txt

Example2: Save a file with line numbers included in the file

cat -n filename.txt > file2.txt

Example3: Display line number of a file along the content using nl command
nl filename.txt

Example4: How can I count number of lines in a file?

cat filename.txt | wc -l

Example5: Display line numbers using sed command.
sed = tem.txt | sed ‘N;s/n/t/’

Through Shell script


#!/bin/bash
j=0

for i in `cat filename.txt`

do

let j+=1

echo “$j $i”

done

Please feel free to add your own way of listing file content along with line numbers.
The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.