Add Line Numbers to grep Output

Often you will grep for certain strings in a text file, but need to find which line it’s on within that file. On a standard grep output, you will see the output, but have no idea which line the string has been found on.

grep has an option, -n, which resolves that.

As an example, imagine we’re grep’ing a text file for the word “line”:

$ grep "line" example-file.txt
This is line 1
This is line 3
This is line 5
This is line 7
line
Another line
And Another line

We have found every instance of “line” in example-file.txt, however, if we wanted to find these quickly in a text editor, we wouldn’t know which line to go to. ¬†Therefore, we add the -n option:

$ grep -n "line" example-file.txt
1:This is line 1
3:This is line 3
5:This is line 5
7:This is line 7
9:line
10:Another line
11:And Another line

Now, we have the line number as part of the output, and we can instantly jump to that line in our favourite text editor. (Which is Vim, right?)

Add Line Numbers to “cat” Output

cat¬†can be used to print the contents of a file in a Terminal, and it’s often useful to number each line of the output (including empty lines).

Adding line numbers is as simple as adding the -n switch to the command:

cat -n filename.txt

Example Output, with -n switch:

$ cat -n filename.txt

1 Line 1
2 Line 2
3 Line 3
4 Line 4
5 Line 5

Example Output, without -n:

$ cat filename.txt

Line 1
Line 2
Line 3
Line 4
Line 5