Numbering Each Line in a Text File

Sometimes we are given an error message that references a line number in a text file. We can number each line so we can find the error message right a way. In fact, we can print out the exact line that contains the error. This is often useful for finding errors in PHP. If there is an error in the syntax of PHP it will give you the line number it is on. Often times I don’t work in an environment that shows line numbers and I am not about to count each line by hand.

To print out the exact line with cat you can use:

$ cat -n someFile.txt | grep -w 500

This would print out the 500th line.

Command Breakdown

 
cat - this command will concatenate (print) text.
-n - the ‘n’ switch tells cat to add line numbers.
| - the | or AKA pipe will take the results from ‘cat -n’ and pipe them to grep
grep - this is a text search program. This will look for certain strings
-w - the w command tells grep to only match whole words
500 - this is the “word” we are looking for.

Adding Line Numbers to Vim

 
Open the file with Vim:

$ vim someFile.txt

Then add the show line numbers option by typing the following:

:set number




No Comment
No comments yet
Leave a reply