在多个文件中搜索

xra*_*alf 6 command-line find search

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

我尝试了这个基本技术

for i in `find .`; do grep searched_string "$i"; done;
Run Code Online (Sandbox Code Playgroud)

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

Nik*_*ley 10

你可以做任何一个

grep pattern_search . # 在当前目录上做一个普通的 grep

grep pattern_search * # 对当前目录中的所有 globbed 文件使用普通的 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. 
Run Code Online (Sandbox Code Playgroud)

  • 第一种形式,`grep pattern .` 不搜索任何文件,没有递归选项。 (4认同)

Chr*_*ard 6

我用:

find . -name 'whatever*' -exec grep -H searched_string {} \;
Run Code Online (Sandbox Code Playgroud)