Search This Blog

Friday, 13 May 2011

Easily add line numbers to a text file

You can easily hardcode line numbers into 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


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.