Tag Archives: tips

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

 

“Ping Hostname” Returning an IPv6 Address Instead of IPv4? (Windows)

On Windows based PCs and Servers, and where IPv6 is enabled on one of the network adapters, you may find that when you do a:

ping name-of-host

… you get an IPv6 address returned in the results.  But what if you want to test IPv4 connectivity?  You can add a -4 switch to the ping command to force it to use IPv4 as follows:

ping -4 name-of-host

Ping will now ping the IPv4 address as opposed to the IPv6.

It’s worth noting, that if you do want to test for IPv6 connectivity, you can add a -6 switch to force that:

ping -6 name-of-host