1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Linux】内容に特定の文字列を含むファイルのパスを取得する方法

Posted at

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を含むファイルのパスが取得できました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?