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
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
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?)
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
grep is a great way to find phrases, words, and characters in text. One of the biggest stumbling blocks is case – is the word “Hello”, “hello”, “HELLO”, or even “HeLLo”? All of these are different, and a “grep “Hello”” would only find lines containing the first “Hello” example.
You can, however, exclude case from a grep to make it not case sensitive – simply add -i:
grep -i “Hello” textfile.txt
Alternatively, you could use it in conjunction with cat and tac (Reverse Cat)
cat textfile.txt | grep -i “Hello”
The above will find all lines containing “Hello” in textfile.txt, whether it’s “Hello”, “HELLO”, HElLO”, etc, making it much easier to find instances of “Hello” if you don’t really need to care about case.
(Read the article on Wikipedia about Case Sensitivity..)