grep
コマンドで取得
grep
コマンドを使用して内容に特定の文字列を含むファイルのパスを取得するには以下のように実行します。
grep -lr '検索する文字列' 対象のパス
-
-l
一致するものが含まれているファイルのパスのみ表示する。 -
-r
ディレクトリを指定した場合にサブディレクトリ内のファイルも含めて検索する。
以下のようにファイルを作成し実際に実行してみます。
$ tree
.
└── sample
├── example.txt
└── test.txt
$ cat ./sample/example.txt
ABCDE
$ cat ./sample/test.txt
12345
$ grep -lr '1' ./sample
./sample/test.txt
1
が含まれているtest.txt
のパスが出力されました。
find
コマンドで取得
find
コマンドを使用しても上記と同様のことができます。
find
コマンドの場合には以下のようにします。
find 対象のパス -type f -exec grep -l '検索する文字列' {} +
または以下のようにします。
find 対象のパス -type f | xargs grep -l '検索する文字列'
$ find . -type f -exec grep -l '1' {} +
./sample/test.txt
$ find . -type f | xargs grep -l '1'
./sample/test.txt
find
コマンドでも1
を含むファイルのパスが取得できました。