在许多文件中搜索

在许多文件中搜索

是否有一些复杂的技术可以在许多文件中搜索字符串?

我尝试了这个基本技术

for i in `find .`; do grep searched_string "$i"; done;

它看起来并不复杂,而且在文件层次结构中没有发现任何内容。

答案1

您可以执行以下任一操作

grep pattern_search . # 在当前目录上执行普通的 grep

grep pattern_search * # 对当前目录中的所有通配文件使用普通 grep

grep -R pattern_search . # 在当前目录中使用递归搜索

grep -H pattern_search *# 当文件超过一个时打印文件名。 '-H'

其他选项例如(来自 gnu 手册):

--directories=action
    If an input file is a directory, use action to process it. By default, 
    action is ‘read’, which means that directories are read just as if they 
    were ordinary files (some operating systems and file systems disallow 
    this, and will cause grep to print error messages for every directory 
    or silently skip them). If action is ‘skip’, directories are silently 
    skipped. If action is ‘recurse’, grep reads all files under each 
    directory, recursively; this is equivalent to the ‘-r’ option. 
--exclude=glob
    Skip files whose base name matches glob (using wildcard matching). A 
    file-name glob can use ‘*’, ‘?’, and ‘[’...‘]’ as wildcards, and \ to 
    quote a wildcard or backslash character literally. 
--exclude-from=file
    Skip files whose base name matches any of the file-name globs read from 
    file (using wildcard matching as described under ‘--exclude’). 
--exclude-dir=dir
    Exclude directories matching the pattern dir from recursive directory 
    searches. 
-I
    Process a binary file as if it did not contain matching data; this is 
    equivalent to the ‘--binary-files=without-match’ option. 
--include=glob
    Search only files whose base name matches glob (using wildcard matching 
    as described under ‘--exclude’). 
-r
-R
--recursive
    For each directory mentioned on the command line, read and process all 
    files in that directory, recursively. This is the same as the 
    --directories=recurse option.
--with-filename
    Print the file name for each match. This is the default when there is 
    more than one file to search. 

答案2

我用:

find . -name 'whatever*' -exec grep -H searched_string {} \;

答案3

在 Chris Card 的答案的基础上,我自己使用: xargs 中的with 组合find . -print0 | xargs -r0 grep -H searched_string 确保文件名中的空格得到正确处理。告诉xargs 在命令行上至少给出一个文件名。如果我想要固定字符串(没有正则表达式),我通常也会使用它,这样会快一点。-print0-0-rfgrep

使用find . -print0 | xargs -0 cmd速度比find . -exec cmd {} \;.它比 -exec+ 稍慢find . -exec cmd {} +,但比 -exec+ 用法更广泛。

答案4

如果在命令中添加 /dev/null,您还将获得该字符串匹配的文件名:

for i in `find .`; do grep searched_string "$i" /dev/null ; done;

相关内容