6

I'm trying to find out which version of hibernate the project depends on (this is orthogonal to my question).

We have a parent project with several sub projects, and I know this is defined in one or more pom.xml. The problem is that when it prints a match all it's telling me is the line and that it was found in pom.xml, I want to know which sub project pom.xml.

How can I get grep to print the relative path (absolute would work too but less pretty)? If it's not possible alternative suggestions welcome.

$ grep -rI -3 org.hibernate pom.xml
mdpc
  • 6,834
xenoterracide
  • 59,188
  • 74
  • 187
  • 252

4 Answers4

3

I'd suggest using a combination of find, xargs and grep:

 cd top-dir
 find . -print -name 'pom.xml' -print0 | xargs -0 grep -l pattern

I put in -print0 / -0 option so that special characters in the found directories are protected and properly processed.

The above will list the filename(s) relative to the top-dir matching the patterm.

mdpc
  • 6,834
  • this should be more efficient than xargs, but accomplishes the same (including the too many args problem) find . -name 'pom.xml' -exec grep -3 'org.hibernate' '{}' + – xenoterracide May 01 '14 at 15:09
0
grep --with-filename -rI -3 org.hibernate pom.xml

From the man page:

       -H, --with-filename
          Print  the  file  name for each match.  This is the default when there is more than one file to
          search.
  • this is the default behavior, it does not give the relative or absolute path, I can't tell the difference between one pom.xml and another with this (or maybe this option is ignored...) . Also this is not in my man page... are you sure this is for a freebsd grep and not gnu grep? – xenoterracide May 01 '14 at 14:59
  • GNU Grep. That would be the issue, here. – Dan Garthwaite May 01 '14 at 19:51
0

Another solution is to use a globstar pattern, i.e. a recursive glob, in combination with the grep -H option to include the file name in the output.

shopt -s globstar
grep -H org.hibernate **/pom.xml

Unlike the recursive grep (-R), with this approach, the -H option does include the file path in the output.

Hint: you might find it useful to add shopt -s globstar to your .bashrc to permanently allow recursive globbing.

rustyx
  • 319
0

Just use the following command:

cat */demo.txt | grep -Rli 'demo'

This command will return the path of file.

AdminBee
  • 22,803