Pages

Monday, August 13, 2012

Linux/Unix shell script to number the lines of a file

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.

0 comments:

Post a Comment