Easily Add Line Numbers to a Text File with the Command Line

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… we’ll show you exactly how to do it! To be completely clear, what this is going to do is add a counting line number to the left side of each new line of text, prefixing each line with the appropriate corresponding number. This hard codes it into the text file, which means it’s different from simply showing line numbers in an app like TextWrangler, VIM, or BBEdit.

To get started, get to the Terminal and you’ll want to do the following at the command line prompt:

Using cat to Add Line Numbers to a Text File

This is by far the easiest method:cat -n file > file_new

Simply replace “file” with the file name you want to add line numbers to, and change “file_name” to the exported name.

You can also use the ‘nl’ command as described next:

Hard Core Line Numbers into a Texts File Using the nl Command

Again, replace “filename” and “filenamenumbered” with the appropriate name of the file you are adding line numbers to:

nl -ba -s ': ' filename > filenamenumbered

That’s all there is to it! You can use either trick. Several readers chimed in the comments to provide easier solutions to numbering lines within a text file. They were listed above in order of simplicity, but we’ll offer an ‘awk’ solution below too.

—

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.

Enjoy this tip? Subscribe to the OSXDaily newsletter to get more of our great Apple tips, tricks, and important news delivered to your inbox! Enter your email address below: