Wednesday, February 14, 2007

Display Line Numbers for a File to STDOUT

The UNIX nl utility displays the line numbers for a file to standard output. It can useful during a debugging session. If you use the nl command without options, it does not show line numbers for the blank lines.

Without options
# nl sysad.txt
1 This blog's
2 content
3 is primarily
4 a HOWTO for UNIX
5 system administration.
6 Its articles consist of Solaris,
7 Sybase, Oracle, and miscellaneous
8 tips and operating system information.

9 This blog's content
10 is primarily
11 a HOWTO for UNIX
12 system administration.
13 Its articles consist of Solaris,
14 Sybase, Oracle, and miscellaneous
15 tips and operating system information.

Show the blank line with a line number
# nl -ba sysad.txt
1 This blog's
2 content
3 is primarily
4 a HOWTO for UNIX
5 system administration.
6 Its articles consist of Solaris,
7 Sybase, Oracle, and miscellaneous
8 tips and operating system information.
9
10 This blog's content
11 is primarily
12 a HOWTO for UNIX
13 system administration.
14 Its articles consist of Solaris,
15 Sybase, Oracle, and miscellaneous
16 tips and operating system information.

Print the numbered output
# nl
-ba sysad.txt | lp

4 comments:

David said...

Like you said nl is a great utility for debugging. I actually did not know about this one so I had written a script to do it:

#!/bin/bash
I=1; cat $1 | while read LINE; do echo "$I: $LINE"; ((I++)); done

Thanks for the tip! Now I can stop using my script.

esofthub said...

Glad to help and thanks for the comment.

Frankengeek said...

Good call on the nl command. I teach that one in my Unix for beginners class. The following are some other ways to display line numbers:

Add a line number to all lines.

cat -n

Display a line number on all none blank lines.

cat -b

Display line numbers within the vi editor.

:set nu

esofthub said...

frankengeek...good supplements. Thanks