• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

Using grep to search in reverse

by admin

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

Filed Under: Linux

Some more articles you might also be interested in …

  1. Understanding Samba utilities – nmblookup, smbstatus, smbtar, testparm, wbinfo, smbget
  2. How to Clone Linux disk partition over network using dd
  3. ifconfig Command Examples in Linux
  4. How to Automatically Run ntpdate When Starting NTPD in CentOS/RHEL 5
  5. CentOS / RHEL : How to create and host yum repository over httpd
  6. Error “530: permission denied” when user logs in to vsftpd server via ftp
  7. How to Set “dev_loss_tmo” Value Persistently Using Udev Rule
  8. CentOS / RHEL 7 : How to remove rescue image using grubby
  9. Installing CentOS / RHEL 7 (step by step with screen shots)
  10. Wallch (Wallpaper Changer) – Rotate Ubuntu Desktop Wallpapers

You May Also Like

Primary Sidebar

Recent Posts

  • vgextend Command Examples in Linux
  • setpci command – configure PCI device
  • db_load command – generate db database
  • bsdtar command – Read and write tape archive files

© 2022 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright