Insert line numbers in files painlessly with nl

Was trying to figure out how to insert line numbers into a huge file with sed or awk, then stumbled across "nl", a sweet little baby that comes with GNU coreutils and numbering files is what it does for a living. GNU coreutils is full of gems!

Boring:

ak@gd:~$ cat file
blah
blah blah
bleh blah

Awesome:

ak@gd:~$ cat file | nl -n ln -w1 -s\|
1|blah
2|blah blah
3|bleh blah

More awesome (avoids UUOC):

ak@gd:~$ nl -n ln -w1 -s\| file
1|blah
2|blah blah
3|bleh blah

3 Comments

  • 1. Clinton Cronin replies at 27th May 2010, 2:19 pm :

    It seems to use single digits. Is there a way to let it go to double and triples?

    I promptly stole and made a bash script out of this (though largely overkill) it comes in handy.

    #!/bin/bash
    file=$1
    cat $file | nl -n ln -s'|'
  • 2. Alain Kelder replies at 27th May 2010, 2:43 pm :

    What’s up Clinton!

    The syntax of “nl” seems a bit awkward, for me at least, but looks like you could do it like so:

    $ cat file | nl -n rz -w3 -s\|
    001|blah
    002|blah
    003|blah
    004|blah
    005|blah
    006|blah
    007|blah
    008|blah
    009|blah
    010|blah
    011|blah
    012|blah
    013|blah
    014|blah
    015|blah
    016|blah
    017|blah
    018|blah
    019|blah
    020|blah
  • 3. Alain Kelder replies at 27th May 2010, 2:55 pm :

    Another little thing I ran into with it recently is that by default, it skips blank lines:

    $ head -4 file | nl -n rz -w3 -s\|
    001|blah
     
    002|blah
    003|blah

    To number blank lines as well:

    $ head -4 file | nl -n rz -ba -w3 -s\|
    001|blah
    002|
    003|blah
    004|blah

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).