How to use grep to search a file in reverse

Written by kevin walker
  • Share
  • Tweet
  • Share
  • Email

Grep is a powerful Unix/Linux command-line utility for searching large files, such as computer log files, to pinpoint lines which contain the desired information. For example, in a long computer log file, the user may only wish to see lines that contain the word "ERROR." He would type the following into the Unix terminal:

grep "ERROR" logfile.log

However, often the most important information in a file is located at the end of the file, rather the beginning. It would be handy if there was a command flag to tell grep to search the file in reverse, but unfortunately that is not an option. Instead, we must reverse the file using another application and "pipe" the data to the grep program. This is a common operation in Unix and Linux scripting: chaining simple utilities together to produce complex results.

Skill level:
Easy

Other People Are Reading

Instructions

  1. 1

    Open your terminal. How you do this will depend on your operating system version.

  2. 2

    Type the following command:

    tac logfile.log

    You should replace the filename of "logfile" with the file you would like to use. Tac is a Unix command that reverses the order of the lines within the file and prints the results to the console. Hit enter to see the results.

  3. 3

    Repeat the last command and add the "pipe" command to it, followed by the grep command you would like to run. For example:

    tac logfile.log | grep "ERROR"

    This will first reverse the line order of the file "logfile.log." Then, rather than printing that to the screen, it will pipe it to grep, which will search for lines containing the word "ERROR."

Tips and warnings

  • The pipe symbol is not a one (1) or a lower-case L (l). Instead it is the vertical bar (|) which can be inserted by hitting the "\" key with the SHIFT key held down (on a standard U.S. keyboard).

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.