views:

265

answers:

5

Hello I am using this command to find text within files in linux

find ./ -type f -exec grep -l "Text To Find" {} \;

The command works fine, but I would like to print automatically the line that contains the text or if it is possible the firs two lines above the text and the two lines behind the text.

Also another suggestions to find text and print the lines instead of using find are welcome,

Thanks a lot in advance.

+7  A: 
find ./ -type f -exec grep -Hn "Text To Find" {} \;

Use -A and -B flags to print lines before and after the match:

find ./ -type f -exec grep -Hn -A1 -B1 "Text To Find" {} \;

also you can just use grep:

grep -R -Hn -A1 -B1 "Text To Find" *
mletterle
+2  A: 

Why not just grep?

grep -r -C2 "Text To Find" *
Chris J
Because the `-r` option is not portable (as a matter of fact neither is `-C` but hey, he asked for it. :) )
vladr
The poster did say "Also another suggestions to find text and print the lines instead of using find are welcome" and tagged the question "linux", so GNU grep is probably fine.
Andrew Medico
+1  A: 

To print the lines (with the file that contains it):

find . -type f -exec grep "text" {} /dev/null \;

To see 2 lines following the line that matches add -A2 after "grep" in the above line, -B2 for the two lines before, and -C2 for both.

Johnny Edge
+1  A: 
find ./ -type f -exec egrep -H -B 2 -A 2 "Text" '{}' ';'
Quassnoi
+3  A: 

You may use the following alternate find construct for a faster search:

find . -type f -print0 | xargs -0 grep -Hn -C2 "Text To Find"

Instead of invoking grep for each and every file (which is what -exec ... {} does), it will invoke grep for bunches of files.

Note that the -print0, -0 and -C2 options are not portable (will work fine with the GNU variants of the find, xargs and grep programs i.e. most Linux, BSD etc. installations as well as Cygwin and MinGW, but do not expect them to work with "older" Solaris, HPUX etc. installs.)

Cheers, V.

vladr
And be sure to use "-print0" for find and "-0" on xargs. This will help with files that have spaces in their names by using NULL as a delimiter rather than spaces.
Andy