LoginSignup
57

More than 3 years have passed since last update.

【Linux】特定の文字列を含むファイル名を表示する

Last updated at Posted at 2018-12-11

特定の文字列を含むファイルを探す方法をメモしました。

grepコマンドを使います。

参考記事

grepコマンドの詳細まとめました【Linuxコマンド集】

【 grep 】コマンド――特定の文字を含む行を抽出する

【find・grep】特定の文字列を含むファイルのリストを取得する方法。

ファイル名のみ表示

指定したディレクトリ以下を再帰的に検索し、検索対象の文字列が存在するファイル名を表示します。

$ grep -ril "文字列" ディレクトリのパス
  • git_testディレクトリ内にある"first"を含むファイルを検索した結果
$ grep -ril "first" git_test
git_test/test_01.txt
git_test/test_02.txt
git_test/testdir/test_03.txt
git_test/testdir/test_04.txt

ファイル名と該当行を表示

指定したディレクトリ以下を再帰的に検索し、検索対象の文字列が存在するファイル名と該当行を表示します。

$ grep -rin "文字列" ディレクトリのパス
  • git_testディレクトリ内にある"first"を含むファイルを検索した結果
$ grep -rin "first" git_test
git_test/test_01.txt:3:first
git_test/test_02.txt:3:first
git_test/testdir/test_03.txt:3:first
git_test/testdir/test_04.txt:3:first

今回使用したオプション

-r(--recursive)

サブディレクトリ内も含めて(再帰的に)検索する。

-i(--ignore-case)

大文字・小文字を区別しない。

-l(--files-with-matches)

検索結果にファイル名のみ表示する。

-n(--line-number)

行番号を表示する。

fgrepコマンド

今回はgrepを使用しましたが、正規表現を使用しなければfgrepで高速検索ができるそうです。

拡張子を指定した絞り込み

  • 平成30年12月12日追記

以下の書き方で、特定の文字列を含むtxtファイルの名前のみを表示する事ができます。
探したいファイルの拡張子がハッキリしている場合は便利です。

$ find ディレクトリのパス -name "*.txt" | xargs grep -l "文字列"

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
57