Recursively search for files of a given name, and find instances of a particular phrase AND display the path to that file
Asked Answered
L

2

11

I have a bunch of folders and subfolders. Each one contains, amongst other things, a text file called index.yml with useful data. I want to search through all of the different index.yml files to find instances of a search string. I must be able to see a few lines of context and the directory of the index.yml file that was found.

This almost works, but it doesn't give me the filename:

cat `find . -name 'index.yml'`| grep -i -C4 mySearchString

How can I do this and get the filename?

I am stuck on Windows with using msys. Note I don't seem to have full GNU grep, so I can't run grep --exclude or grep -R as suggested in other SO questions.

Lankester answered 21/8, 2010 at 21:6 Comment(0)
A
10

try this:

find -name "index.yml" -exec grep -i -H -C4 pattern {} \;

note: not actually tested under msys.

Ale answered 21/8, 2010 at 21:14 Comment(5)
This is the right answer for a normal unix like system. I couldn't get something like this, or an xargs variety to work on cygwinToccaratoccata
Great! Thanks. As soon as SO lets me.. i will accept this answer. Seems to be some time limit.Lankester
@Lankester {} is replaced with a filename (or directory name) find found. \; denotes the end of the arguments for exec. the slash is to escape the semicolon from the shell. sometimes it is also necessary to escape the {}.Ale
That's a "backslash" not a "slash".Lucas
on osx had to specify a path to search, find . -name "index.yml" -exec grep -i -H -C4 pattern {} \;Richard
U
0

One possibility (I don't know what msys accepts exactly):

 find . -name index.yml -exec grep -i -C4 mySearchString /dev/null {} +

The /dev/null serves to ensure there are at least two pathnames so that the pathname is printed with each match. The -H option to grep has a similar effect.

The -exec...+ construct in find causes multiple pathnames to be passed to a single instance of the command. If it is not implemented, you'll have to use -exec...\;.

Undersheriff answered 21/8, 2010 at 21:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.