Bash – Shell program which reads line and output lines with the line numbers

bashshell-script

I need to write a program that reads lines from a file on stdin and writes the lines to stdout with line numbers. I cannot use cat -n.

Let's say the text file had this:

 abcdef
 ghi

 klm
 nopqr st

It should basically read those lines and output those lines but with lines numbers.

This is the while read loop I have but it doesn't print out every line.

while read line
do
    awk '{print NR, $0}'

done < file

Basically what this output is this:

1 ghi
2 
3 klm
4 nopqr   st

For some reason the abcdef doesn't show up and number 2 isn't supposed to be blank.

Best Answer

Have you tried nl -b a <file_name>

debian@virt00:~/test$ nl -b a file
     1  abcdef
     2   ghi
     3
     4   klm
     5   nopqr st
debian@virt00:~/test$
  • nl stands for number line
  • -b flag for body numbering
  • 'a' for all lines.

for more information http://linux.die.net/man/1/nl

Related Question