grep question

After reading the recent thread about using grep to return <match> + X following lines, would it be possible to use grep to recursively return the below or is a shell script needed?

<path>
<match>
X following lines

I have a directory, $WORK, which has several subdirectories. Each of these subdirectories has an identical filename that I want to use grep on but I want to echo the path to know which grep results came from which file (and it is the pathname that provides the unique file identifier since the filenames are identical).

Thanks!

If you supply a list of filenames on the command line, grep will prefix matches with the filename. E.g.

grep -A 2 */file

will give as output:

dir1/file:match
dir1/file:after1
dir1/file:after2
dir2/file:match
dir2/file:after1
dir2/file:after2

and so forth. Not exactly the format you want, but if you just want to know where the matches were, it might do. Otherwise you can figure out a way to postprocess that output to the format you want.

That will work for what I want - maybe even better than my original thought - thank you very much!

A followup - doing that, the files will all need to live in the same relative hierarchy level? So if some files are */file and others //file I’d need to do

grep -A 2 */file >summary;grep -A 2 //file >>summary

replacing the 2 with the actual number of lines I want to trail, right?

I’m really interested in lines 10 - 20 after <match1>, a unique identifier in the original file. Line 9 always has <match2>, an identifier prior to lines 10 - 20, but it is not unique in the original file. Is there a direct way to use grep to get lines 10 - 20, or would I need to make summary as above (grep -A 20 match1 */file >summary;grep -A 20 match1 //file >>summary) and then do

grep -A 11 match1 summary >summary2

?

Thanks again!

You can combine them:

grep -A 2 */file */*/file >summary

I’m really interested in lines 10 - 20 after , a unique identifier in the original file. Line 9 always has , an identifier prior to lines 10 - 20, but it is not unique in the original file. Is there a direct way to use grep to get lines 10 - 20, or would I need to make summary as above (grep -A 20 match1 */file >summary;grep -A 20 match1 //file >>summary) and then do

grep -A 11 match1 summary >summary2

You mean

grep -A 11 match2 summary >summary2

I think. Hope that works.