Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the line that matches my text using find in linux?

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.

like image 361
Eduardo Avatar asked Feb 20 '09 22:02

Eduardo


People also ask

How do I print a specific line of text in Linux?

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.

How do you search for lines of text in Linux?

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.

How do you get a specific line from a file Linux?

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.


3 Answers

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" *
like image 53
mletterle Avatar answered Oct 07 '22 23:10

mletterle


Why not just grep?

grep -r -C2 "Text To Find" *
like image 33
Chris J Avatar answered Oct 07 '22 23:10

Chris J


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.)

like image 43
vladr Avatar answered Oct 07 '22 23:10

vladr