Wednesday, June 15, 2011

5 different ways to do numbering of a file contents



  Sometimes, we might have a requirement wherein we need to display the file contents with its line number. In this article, we will see the different ways in which we can achieve this line numbering of file.

Let us take a sample file, say file1, with the following contents:


$ cat file1
Ashwath, Mangalore
Abirami, Chennai
Swetha, Karwar
1. Unix has a specific command, nl, whose very purpose is to do line numbering. This command is very rarely known or used:
$ nl file1
     1  Ashwath, Mangalore
     2  Abirami, Chennai
     3  Swetha, Karwar
2. The simplest of all is using the cat command. cat command has an option "-n" which exactly does this line numbering.
$ cat -n file1
     1  Ashwath, Mangalore
     2  Abirami, Chennai
     3  Swetha, Karwar
3. awk can also be used to get the line numbering using the awk special variable, NR.
$ awk '{print NR, $0}' file1
1 Ashwath, Mangalore
2 Abirami, Chennai
3 Swetha, Karwar
  NR contains the line number of the line being processed by awk currently. And hence the above output.

4. perl has a special variable, $., which is same as the NR of awk, gives line number at any point of a file.
$ perl -ne '{print $.,"  ", $_}' file1
1  Ashwath, Mangalore
2  Abirami, Chennai
3  Swetha, Karwar
5. sed command can be tweaked a bit to get the line numbering:
$ sed '=' file1 | sed 'N;s/\n/  /'
1  Ashwath, Mangalore
2  Abirami, Chennai
3  Swetha, Karwar
    To understand the above sed command, you need to execute the commands separately. The '=' operator gives a line number to every line. However, the line number is one line, the contents move to the next line. In order to join the number and the file contents, we use the 'N' function of sed to join it. Using 'N', we substitute the new line character by 2 spaces, and hence the result as above.

Happy Numbering!!!!
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment