
多くのファイルから文字列を検索する洗練された技術はありますか?
この基本技術を試してみました。
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 *
#ファイルが2つ以上の場合はファイル名を出力します。 「-時間」
(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の答えに基づいて、find . -print0 | xargs -r0 grep -H searched_string
ファイル名のスペースが正しく処理されるように、xargsの組み合わせと一緒に私自身のものを使用しました。コマンドラインに少なくとも1つのファイル名を指定するようにxargsに指示します。私は通常、固定文字列(正規表現なし)が必要な場合は通常これを使用します。少し速いです。-print0
-0
-r
fgrep
-exec+より少し遅いですが、-exec+よりも広く使用されていますfind . -print0 | xargs -0 cmd
。find . -exec cmd {} \;
find . -exec cmd {} +
答え4
コマンドに/dev/nullを追加すると、その文字列に一致するファイル名も取得できます。
for i in `find .`; do grep searched_string "$i" /dev/null ; done;