Grep - linux find file in directory with given string in content

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

In Linux (command line):

I need to find all Perl-files (filename ends with .pl or .pm) that are located in /users/tom/ or any of its sub-directories and which contain both the string ->get( and the string #hyphenate (located in different lines or in the same line). I just need the names of the files (and their path s). I don t need the lines within the file where the strings was found.

Is there a command that can do this?

I know how to find files with one extension:

find /users/tom -name "*.pl"  

But i have troubles to find files, that have one of two different extensions. None of this commands works:

find /users/tom -name "*.pl" -name "*.pm"  
find /users/tom -name "*.pl|*.pm"  

My workaround is to do it one after the other, but I guess there must be a more elegant way.

Now for the file s content:
I know how to print filenames and matching lines with grep:

grep * -e "->get(" -e "#hyphenate"  

This lists all files that contain at least one of the search-strings. But I want a list of files that contain all search-strings.

How can this be done? (Form command-line in Ubuntu/Linux)

Answers

grep can recursively search directories with -r. To only get file names, not the matching lines, use -l.

grep -rl --  ->get(|#hyphenate  /users/tom | grep  .p[lm]$ 

Or, with find:

find /users/tom -name  *.p[lm]  -exec grep -l --  ->get(|#hyphenate  {} +

Update

The above searches for ->get( or #hyphenate, if you want both, you have to run grep twice:

find /users/tom -name  *.p[lm]  -exec grep -l --  ->get(  {} + 
| xargs grep -l  #hyphenate 

If your file names contain whitespace, you might need to specify -Z for the first grep and -0 for xargs.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/33709081/linux-find-file-in-directory-with-given-string-in-content

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils