Using grep to search in reverse

Imagine that you have a large text file and you are looking for a specific piece of information or want to find every occurrence of something. For me, this is a daily occurrence, as I look through system logs when trying to solve problems. This brings us to the grep command.

grep, which is used to search for a string or a pattern in the input, always starts searching from the beginning of the file. But if we wanted to start the search from the back that is from the last line, then we can use grep in combination with tac.

tac displays the content of a file from the last line to the first line, if this is piped to grep it will be able to search in the reverse. For example, if we have a file with the name test_file.

# cat test_file
Linux was created in 1991
It is a very robust and flexible OS.
It follows POSIX standards
There a huge number of distros in linux.

If we want to search for the string distros which is at the end we can use:

tac test_file | grep distros

grep reverse: how to reverse the meaning of a `grep` search

reversing the grep means simply exclude the lines which contain a search term. To do this, use the ā€œ-vā€ switch with the grep command. For example:

$ grep -v "exclude text" filename

To get more information on grep command options, take look at the grep man page.

$ man grep
Related Post