Easily add line numbers to a text file
Brian asks: “I need to add line numbers to a text file. I don’t mean line numbers in the text editor, I mean adding a number next to each item inside a text file. Is this possible to automate or do I have to manually edit the file typing 1, 2, 3 and going insane?”
Yes, you can easily hardcode line numbers into a text file…
Update: Several readers chimed in the comments to provide easier solutions to numbering lines within a text file. In order of simplicity:
Using cat (by far the easiest method):
cat -n file > file_new
Using the nl command:
nl -ba -s ‘: ‘ filename > filenamenumbered
Thank you Steven and Bernhard!
–
You can also use the command line tool ‘awk’, but it’s a bit more complex than the methods mentioned above, if you’re interested launch the Terminal and away we go.
First, be sure to backup your text file in the odd event something goes wrong (like a syntax error). Now that you’ve made a backup of the text file in question, let’s write line numbers directly into it:
awk '{printf("%5d : %s\n", NR,$0)}' filename > filenamenumbered
filename is the original file, and filenamenumbered is whatever you want to call the output of the awk command with line numbers attached to it. Your output text document will now have a number followed by a colon before each line item:
1: line with words
2: line with words
3: line with words
Your original text file should be unchanged, but if you made a syntax error than the backup file you made will save your day. This command will work in any Unix OS that has awk support, so feel free to run this command in FreeBSD, Linux, Mac OS X, or whatever other variant you can think of.

Note that there is a specific tool for this: nl. This command should get you the same output as the more complicated awk above
nl -ba -s ‘: ‘ filename > filenamenumbered
The command cat can do the same:
cat -n file > file_new
Nice call on cat – I didn’t know that one. I think in order of increasing flexibility: cat, nl, awk.
Thanks Bernhard and Steven, I didn’t know about either of those methods. Post has been updated!
Thanks for the command. I’ve adapted the command to add C-style comments with counts and added it to http://www.commandlinefu.com/commands/view/7562/add-line-number-count-as-c-style-comments.