How To: Grep Tricks for Linux Users

By  

The first of these tricks allows you to create a list of files that contain whatever string you are looking for. It uses the -l (list just the file names, not the matched content) option plus the -r option for recursing through subdirectories. This can help you find files that you might be looking for without distracting you with all the reasons particular files matched your search criteria.

grep -rl "string you want to find" *

Example:

$ grep -rl "meeting minutes" *
ARK2010/02-02-notes
ARK2010/TBD
Jan2010/TASkForce2
Mar2010/TaskForce2

Another useful trick with grep on Linux allows you to specify a Perl regular expression in your search term. In this example, we can give grep an expression that allows it to match on mulitple strings, much like egrep. You can get far more complicated than the examples shown, but here's the basic syntax:

grep -P "while|for" *
grep -P 'photo\.gif' *

You can also combine grep with find commands to get some useful extractions of text from target files.

find . -name "*.r" -exec grep "rho" '{}' \; -print

Of course, one of the most useful grep tricks that I've come across so far is the one that provides some context along with your find. Instead of only displaying the lines containing the specific text you were searching for, you can print lines appearing before and after the matched lines -- often required to determine whether tha "match" is really what you're looking for.

You can specify how many lines you want to see before your matched string with the "B" (for "before") option and the number of lines following the match with the "A" (for "after") option.

$ grep -B 2 -A 2 echo *
--
while1-while [ $n -lt 5 ]
while1-do
while1:    echo hello
while1-     ((n +=1))
while1-done
--
whoison-#!/bin/bash
whoison-
whoison:echo hello, $USER
whoison:echo Look who is logged in!
whoison:echo ===========================
whoison-who | awk '{print $1}' | sort | uniq
whoison:echo ===========================

Notice that more than five lines were displayed in the second block of lines above because "echo" appeared more than once in these lines.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question