Unix Power ToolsUnix Power ToolsSearch this book

12.13. Numbering Lines

There are times when you want to print out a file with the lines numbered -- perhaps because you are showing a script or program in documentation and want to refer to individual lines in the course of your discussion.

This is one of the handy things cat can do for you with the -n option.

cat -n precedes each line with some leading spaces, the line number, and a TAB. How many leading spaces? It depends on how high the line numbers go. The line numbers are right-justified at column 6, which means that a 6-digit number will go all the way back to the margin. I only belabor this point in case you're tempted to trim the leading spaces with something like cut (Section 21.14).

Figure Go to http://examples.oreilly.com/upt3 for more information on: nl

If you have a version of cat that doesn't support -n, try nl, the line-numbering program. nl -ba acts like cat -n. By itself, nl numbers only lines with text. The GNU version is on the web site.

You can achieve a similar effect with pr -t -n. (The -t keeps pr from inserting the header and footer (Section 45.6) it normally uses to break its output into pages.) And as long as we're giving you choices, here are five more:

less -N filename
grep -n \^ filename
awk '{print NR,$0}' filename
sed = < filename | sed 'N;s/\n/ /'
ex - '+%#\|q' filename

--JP and TOR



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.