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.
Using the Linux sed Command There are two effective sed command approaches to reading/printing a particular line from a text file. The first approach utilizes the p (print) command while the second approach utilizes the d (delete) command.
Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.
Using the head and tail Commands The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.
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" *
Why not just grep?
grep -r -C2 "Text To Find" *
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With