How to print a line matching my text using find in linux?

Hello, I use this command to search for text inside files in linux

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

The command works fine, but I would like to automatically print a line containing the text, or, if possible, two lines above the text and two lines after the text.

Other suggestions for finding text and printing strings instead of using find are also welcome .

Thank you very much in advance.

+5
source share
5 answers
find ./ -type f -exec grep -Hn "Text To Find" {} \;

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

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

You can also use grep:

grep -R -Hn -A1 -B1 "Text To Find" *
+14
source

find:

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

grep ( -exec ... {}), grep .

, -print0, -0 -C2 ( GNU find, xargs grep, Linux, BSD .. Cygwin MinGW, , "" Solaris, HPUX ..)

+3

grep?

grep -r -C2 "Text To Find" *
+2

( , ):

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

, , add -A2 "grep" , -B2 , -C2 .

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

All Articles