BioErrorLog Tech Blog

試行錯誤の記録

grepコマンドで特定の文字列を含むファイルを検索する | Linux shell

ある特定の文字列を含むファイルをLinuxコマンドで検索する方法を整理します。

はじめに

こんにちは、@bioerrorlogです。

コードを検索したいときなど、特定の文字列を含むファイルをコマンドで検索したい時があります。

そのたびに毎回コマンド調べているので、今回はそのやり方の備忘録を残します。

ある文字列を含むファイルをコマンドで検索する

やり方

特定の文字列をあるディレクトリ以下で再帰的に検索するには、以下のコマンドを使います:

grep -r [検索する文字列] [検索対象のパス]


使用例:
以下の例ではfuncという文字列を、./srcディレクトリ以下で再帰的に検索します。

$ grep -r "func" ./src
./src/Main.gd:func _ready():
./src/Main.gd:func _process(delta):
./src/Prey.gd:func _physics_process(delta):
./src/Boid.gd:func _ready():
./src/Boid.gd:func _process(delta):
./src/Boid.gd:func set_prey_position(position: Vector2):
./src/Boid.gd:func process_centralization(centor: Vector2):
./src/Boid.gd:func process_cohesion(neighbors):
./src/Boid.gd:func process_alignments(neighbors):
./src/Boid.gd:func process_seperation(neighbors):
./src/Boid.gd:func steer(var target):
./src/Boid.gd:func get_neighbors(view_radius):


また、出力結果をファイル名のみにする場合は、オプションに-lを追加します:

grep -rl [検索する文字列] [検索対象のパス]


使用例:
以下の例ではfuncという文字列を./srcディレクトリ以下で再帰的に検索し、該当のファイル名を出力します。

$ grep -rl "func" ./src
./src/Main.gd
./src/Prey.gd
./src/Boid.gd


解説

それでは、上で紹介したコマンドを一つずつ解説します。

まずgrepは、与えたパターンをファイルから検索するコマンドです。

$ man grep
DESCRIPTION
   grep  searches  for  PATTERN  in  each  FILE.


grepコマンドは、以下の基本文法で使用します:

SYNOPSIS
grep [OPTION...] PATTERNS [FILE...]


上の使用例をこれに当てはめますと:

$ grep -rl "func" ./src

-rlというオプションで、funcというパターンを./srcパスで検索している、ということになります。


ここで-rlは、-rオプションと-lオプションを併用していることを意味しています。

-rオプションは、指定したパス以下を再帰的(recursively)に検索することを指定します。

-lオプションは、出力をファイル名のみに絞ることを指定します。

$ man grep

-r, --recursive
        Read all files  under  each  directory,  recursively,  following
        symbolic  links only if they are on the command line.  Note that
        if  no  file  operand  is  given,  grep  searches  the   working
        directory.  This is equivalent to the -d recurse option.

-l, --files-with-matches
        Suppress normal output; instead print the  name  of  each  input
        file  from  which  output would normally have been printed.  The
        scanning will stop on the first match.


補足: 特定ディレクトリをgrep対象から除外する

.gitディレクトリや.terraformディレクトリなど、容量は大きいけどgrepしなくてよいディレクトリを検索対象から除外したいことがあります。

特定ディレクトリをgrep対象から除外するには、--exclude-dirオプションを使用します。

grep -r "events" . --exclude-dir={.git,.terraform}

--exclude-dir={.git,.terraform}のように、{}内でコンマ区切りに指定することで複数ディレクトリを排除指定できます。

おわりに

今回は、ある文字列を含むファイルをLinuxコマンドで検索する方法を簡単にメモしました。

ちょっとした(しかし面倒くさい)こういった処理をパッとできてしまうのは、コマンド処理のいいところだなと改めて感じます。

[関連記事]

www.bioerrorlog.work

www.bioerrorlog.work

参考

grep(1) — Arch manual pages

How to use the grep command in Linux - Web24

How to Grep for Text in Files | Linode

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