简体   繁体   English

linux在目录中查找具有给定字符串内容的文件

[英]linux find file in directory with given string in content

In Linux (command line): 在Linux中(命令行):

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. 我需要找到位于/users/tom/或其任何子目录中的所有Perl文件(文件名以.pl.pm结尾),并且包含字符串->get(和字符串#hyphenate ( (位于不同的行或同一行)。我只需要文件名(及其路径),不需要文件中找到字符串的行。

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打印文件名和匹配行:

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) (在Ubuntu / Linux中形成命令行)

grep can recursively search directories with -r . grep可以使用-r递归搜索目录。 To only get file names, not the matching lines, use -l . 要仅获取文件名而不是匹配行,请使用-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: 上面的代码搜索->get( #hyphenate ,如果需要两者,则必须运行grep两次:

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指定-Z ,为xargs指定-0

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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