简体   繁体   中英

linux find file in directory with given string in content

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)

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 .

grep -r PLACE_YOUR_STRING_HERE | cut -d ' ' -f 1 | grep '.p1\\|.pm'

将字符串替换为要查找的模式,然后转到要查找的文件夹后运行命令。

find /usr/tom | egrep '*.pl| *.pm' | xargs cat | grep <PATTERN>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM