はじめに
LinuxやUnix環境でテキスト検索を行う際、grepは欠かせないコマンドです。
特に複数のディレクトリや大量のファイルを扱う場合は、再帰的検索を活用することで効率よく目的の文字列を見つけられます。
しかし、オプションの種類が多く、初学者が使い方に迷うことも少なくありません。
本記事では、基本から応用までを解説しています。
参考:GNU grep
grepの再帰的検索の基本構文
ファイル作成
mkdir -p sample/dir1 sample/dir2
ファイル作成
echo "INFO Start" > sample/file1.txt
ファイル作成
echo "ERROR Database connection failed" > sample/dir1/file2.txt
ファイル作成
echo "WARNING Disk usage high" > sample/dir2/file3.log
実行コマンド
grep -r "ERROR" sample
実行結果
sample/dir1/file2.txt:ERROR Database connection failed
仕組み
| 項目 | 内容 |
|---|---|
| grep | テキスト内から指定した文字列を検索するコマンド |
| -r | ディレクトリ配下を再帰的に検索するオプション |
| "ERROR" | 検索対象の文字列 |
| sample/ | 検索開始ディレクトリ |
| 検索結果 | ファイル名:一致した行 の形式で表示される |
解説
grepの再帰的検索では -r オプションを使用し、指定ディレクトリ以下のすべてのファイルを対象に検索します。
ログ解析や設定ファイル調査でよく利用される基本機能です。
grepの再帰的検索で現在のディレクトリを対象にする方法
ファイル作成
mkdir -p logs
ファイル作成
cat << 'EOT' > input.txt
sample text
error message
target string
EOT
ファイル作成
cat << 'EOT' > logs/error.log
error found
target string in log
EOT
実行コマンド
grep -r "error" .
実行結果
./input.txt:error message
./logs/error.log:error found
実行コマンド
grep -r "target" .
実行結果
./input.txt:target string
./logs/error.log:target string in log
仕組み
| 項目 | 内容 |
|---|---|
| コマンド | grep -r "検索文字列" . |
| -r | ディレクトリを再帰的に検索する |
| . | 現在のディレクトリを検索対象にする |
| 検索対象 | カレントディレクトリ配下の全ファイル・サブディレクトリ |
| 出力形式 | ファイル名:一致した行 |
解説
grep -r は指定したディレクトリ以下を再帰的に探索しながら文字列を検索します。
grep -r "error" . のように . を指定すると、現在のディレクトリ全体が検索対象になります。
grepの再帰的検索でファイル名も表示する方法
ファイル作成
cat << 'EOF' > input.txt
sample text
target keyword
subdir target keyword
EOF
ファイル作成
mkdir -p logs
ファイル作成
cp input.txt logs/app.log
実行コマンド
grep -r "target" .
実行結果
./input.txt:target keyword
./input.txt:subdir target keyword
./logs/app.log:target keyword
./logs/app.log:subdir target keyword
実行コマンド
grep -rn "target" .
実行結果
./input.txt:2:target keyword
./input.txt:3:subdir target keyword
./logs/app.log:2:target keyword
./logs/app.log:3:subdir target keyword
仕組み
| 項目 | 内容 |
|---|---|
| grep | テキストを検索するコマンド |
| -r | ディレクトリ配下を再帰的に検索 |
| -n | 一致した行番号を表示 |
| ファイル名表示 | 再帰検索時は一致したファイル名が自動で表示される |
| 検索対象 | . を指定するとカレントディレクトリ以下を検索 |
解説
grep -r を使用すると、サブディレクトリを含めて再帰的に検索できます。
一致した行は ファイル名:内容 の形式で表示されるため、どのファイルに存在するかすぐ確認できます。
grepの再帰的検索で行番号を表示する方法
ファイル作成
cat << 'EOF' > input.txt
sample.txt:apple
logs/app.log:apple
logs/error.log:banana
src/main.txt:apple
EOF
ファイル作成
mkdir -p logs src
ファイル作成
awk -F: '$1=="sample.txt"{print $2}' input.txt > sample.txt
awk -F: '$1=="logs/app.log"{print $2}' input.txt > logs/app.log
awk -F: '$1=="logs/error.log"{print $2}' input.txt > logs/error.log
awk -F: '$1=="src/main.txt"{print $2}' input.txt > src/main.txt
実行コマンド
grep -rn "apple" .
実行結果
./logs/app.log:1:apple
./sample.txt:1:apple
./src/main.txt:1:apple
仕組み
| オプション | 仕組み |
|---|---|
| -r | ディレクトリ配下を再帰的に検索する |
| -n | マッチした行の行番号を表示する |
| "apple" | 検索する文字列を指定する |
| . | カレントディレクトリを検索対象にする |
解説
grep -rn を使用すると、サブディレクトリを含めて再帰的に検索しながら行番号も表示できます。
複数ファイルから対象文字列の位置を素早く特定したい場合に便利です。
grepの再帰的検索で大文字・小文字を区別しない方法
ファイル作成
cat << 'EOF' > input.txt
Apple
apple
Banana
banana
EOF
実行コマンド
grep -ri "apple" .
実行結果
./input.txt:Apple
./input.txt:apple
仕組み
| 項目 | 内容 |
|---|---|
| grep | テキスト検索を行うコマンド |
| -r | ディレクトリを再帰的に検索する |
| -i | 大文字・小文字を区別せず検索する |
| "apple" | 検索対象の文字列 |
| . | カレントディレクトリ以下を対象にする |
解説
grep の -r オプションでディレクトリ配下を再帰的に検索できます。
-i を組み合わせることで、大文字・小文字を区別せずに一致する文字列を検索できます。
grepの再帰的検索で複数キーワードを検索する方法
ファイル作成
mkdir -p logs src
ファイル作成
cat << 'EOL' > logs/app.log
application started
error occurred
warning message
EOL
ファイル作成
cat << 'EOL' > src/main.txt
sample data
sample error data
warning and error
EOL
実行コマンド
grep -rE 'error|warning' logs src
実行結果
logs/app.log:error occurred
logs/app.log:warning message
src/main.txt:sample error data
src/main.txt:warning and error
実行コマンド
grep -r -e 'error' -e 'warning' logs src
実行結果
logs/app.log:error occurred
logs/app.log:warning message
src/main.txt:sample error data
src/main.txt:warning and error
仕組み
| 項目 | 内容 |
|---|---|
| grep | ファイル内容を検索するコマンド |
| -r | 指定ディレクトリ配下を再帰的に検索する |
| -E | 拡張正規表現を有効化する |
| error|warning | OR条件で複数キーワードを検索する |
| -e | 検索パターンを複数指定する |
| grep -rE 'error|warning' logs src | 正規表現で複数キーワードを再帰検索 |
| grep -r -e 'error' -e 'warning' logs src | -e を利用して複数キーワードを再帰検索 |
解説
grep の再帰検索では -r を使用してディレクトリ配下のファイルを対象にできます。
複数キーワードは -E の OR 条件または -e の複数指定で検索できます。
grepの再帰的検索で正規表現を活用する方法
ファイル作成
mkdir -p logs src docs config
ファイル作成
cat << 'EOT' > src/main.py
import os
print("hello")
EOT
ファイル作成
cat << 'EOT' > src/utils.py
def test():
pass
EOT
ファイル作成
cat << 'EOT' > logs/app.log
ERROR Connection failed
EOT
ファイル作成
cat << 'EOT' > logs/debug.log
INFO Debug message
EOT
ファイル作成
cat << 'EOT' > docs/readme.md
grep recursive search sample
EOT
ファイル作成
cat << 'EOT' > config/settings.conf
max_retry=3
EOT
実行コマンド
grep -Er 'ERROR|max_retry=[0-9]+' logs config
実行結果
logs/app.log:ERROR Connection failed
config/settings.conf:max_retry=3
実行コマンド
grep -Er 'def|import' src
実行結果
src/utils.py:def test():
src/main.py:import os
実行コマンド
grep -Eri 'grep.*search' docs
実行結果
docs/readme.md:grep recursive search sample
実行コマンド
grep -Er '^(ERROR|INFO)' logs
実行結果
logs/debug.log:INFO Debug message
logs/app.log:ERROR Connection failed
仕組み
| 項目 | 内容 |
|---|---|
| grep | ファイル内容を検索するコマンド |
| -r | ディレクトリ配下を再帰的に検索する |
| -E | 拡張正規表現を有効化する |
| -i | 大文字・小文字を区別しない |
| ERROR|max_retry=[0-9]+ | OR条件と数値パターンの組み合わせ |
| def|import | Pythonソース内の関数定義やインポート文を検索 |
| grep.*search | grep と search の間に任意の文字列があるパターン |
| ^(ERROR|INFO) | 行頭が ERROR または INFO の行を検索 |
解説
grep -r を使用すると複数のディレクトリ配下を再帰的に検索できます。
-E を組み合わせることで OR 条件や繰り返し指定などの正規表現を活用でき、grepの再帰的検索を柔軟に実行できます。
grepの再帰的検索で特定の拡張子のみを対象にする方法
ファイル作成
mkdir -p logs archive
ファイル作成
cat << 'EOF' > logs/app.log
INFO: Application started
ERROR: Database connection failed
EOF
ファイル作成
cat << 'EOF' > logs/system.txt
ERROR: Disk full
EOF
ファイル作成
cat << 'EOF' > archive/old.log
ERROR: Old log message
EOF
実行コマンド
grep -r --include="*.log" "ERROR" .
実行結果
./archive/old.log:ERROR: Old log message
./logs/app.log:ERROR: Database connection failed
実行コマンド
grep -rn --include="*.log" "ERROR" .
実行結果
./archive/old.log:1:ERROR: Old log message
./logs/app.log:2:ERROR: Database connection failed
仕組み
| オプション | 説明 |
|---|---|
| grep | テキスト検索コマンド |
| -r | ディレクトリを再帰的に検索する |
| -n | 行番号を表示する |
| --include="*.log" | .log 拡張子のファイルだけを検索対象にする |
| "ERROR" | 検索する文字列 |
| . | カレントディレクトリ以下を対象にする |
解説
grep -r を使用するとディレクトリ配下を再帰的に検索できます。
--include="*.log" を組み合わせることで、特定の拡張子のファイルだけを効率的に検索できます。
grepの再帰的検索で特定ディレクトリを除外する方法
ファイル作成
mkdir -p logs/archive src
ファイル作成
cat << 'EOL' > logs/app.log
INFO Application started
ERROR Database connection failed
EOL
ファイル作成
cat << 'EOL' > logs/archive/old.log
ERROR Legacy system error
EOL
ファイル作成
cat << 'EOL' > src/main.py
print("hello")
EOL
実行コマンド
grep -r --exclude-dir=archive "ERROR" logs src
実行結果
logs/app.log:ERROR Database connection failed
実行コマンド
grep -r "ERROR" logs src
実行結果
logs/archive/old.log:ERROR Legacy system error
logs/app.log:ERROR Database connection failed
仕組み
| 項目 | 内容 |
|---|---|
| grep -r | 指定ディレクトリ配下を再帰的に検索する |
| --exclude-dir=archive | archive ディレクトリを検索対象から除外する |
| "ERROR" | 検索する文字列を指定する |
| logs src | 検索対象のディレクトリを指定する |
解説
grep -r はディレクトリ配下を再帰的に検索できます。
--exclude-dir を利用すると、アーカイブ済みログなど不要なディレクトリを除外しながら効率的に検索できます。
grepの再帰的検索で一致した行の前後を表示する方法
ファイル作成
mkdir -p logs
ファイル作成
cat << 'EOF' > logs/app.log
INFO Application started
ERROR Database connection failed
INFO Retrying connection
INFO Retry succeeded
EOF
ファイル作成
cat << 'EOF' > logs/api.log
INFO Request received
WARN Slow response detected
ERROR Timeout occurred
INFO Request finished
EOF
実行コマンド
grep -r -B 1 -A 1 "ERROR" logs
実行結果
logs/api.log-WARN Slow response detected
logs/api.log:ERROR Timeout occurred
logs/api.log-INFO Request finished
--
logs/app.log-INFO Application started
logs/app.log:ERROR Database connection failed
logs/app.log-INFO Retrying connection
仕組み
| オプション | 説明 |
|---|---|
| grep | テキストを検索するコマンド |
| -r | 指定ディレクトリ配下を再帰的に検索する |
| -B 1 | 一致した行の前の1行を表示する |
| -A 1 | 一致した行の後の1行を表示する |
| "ERROR" | 検索対象の文字列 |
| logs | 再帰的に検索するディレクトリ |
解説
grep -r を使用すると、logs ディレクトリ配下のすべてのファイルを再帰的に検索できます。
-B と -A を指定することで、一致行の前後のログも同時に確認でき、エラー発生時の状況把握に役立ちます。
grepの再帰的検索で検索結果件数を集計する方法
ファイル作成
mkdir -p logs
ファイル作成
cat << 'LOG1' > logs/app.log
ERROR Database connection failed
ERROR Timeout occurred
INFO Application started
LOG1
ファイル作成
cat << 'LOG2' > logs/api.log
ERROR Invalid request
ERROR Authentication failed
ERROR Timeout occurred
LOG2
ファイル作成
cat << 'LOG3' > logs/system.log
INFO System started
ERROR Disk full
LOG3
実行コマンド
grep -r "ERROR" logs
実行結果
logs/api.log:ERROR Invalid request
logs/api.log:ERROR Authentication failed
logs/api.log:ERROR Timeout occurred
logs/system.log:ERROR Disk full
logs/app.log:ERROR Database connection failed
logs/app.log:ERROR Timeout occurred
実行コマンド
grep -r "ERROR" logs | wc -l
実行結果
6
仕組み
| 項目 | 内容 |
|---|---|
| mkdir -p logs | ログ格納用ディレクトリを作成する |
| grep -r | 指定ディレクトリ配下を再帰的に検索する |
| grep -r "ERROR" logs | logs配下の全ファイルからERRORを検索する |
| wc -l | 検索結果の行数をカウントする |
| 集計結果 | ERRORに一致した件数を表示する |
解説
grep -r を利用するとディレクトリ配下の複数ファイルを再帰的に検索できます。
検索結果を wc -l にパイプすることで、一致件数を簡単に集計できます。
grepの再帰的検索とfindコマンドを組み合わせる方法
ファイル作成
mkdir -p testdir/src testdir/logs testdir/docs
ファイル作成
echo "sample text
error message
debug log" > testdir/sample.txt
ファイル作成
echo "error found" > testdir/src/main.txt
ファイル作成
echo "error occurred" > testdir/logs/app.log
ファイル作成
echo "grep recursive search" > testdir/docs/readme.md
実行コマンド
grep -r "error" testdir
実行結果
testdir/logs/app.log:error occurred
testdir/sample.txt:error message
testdir/src/main.txt:error found
実行コマンド
find testdir -type f -exec grep -H "error" {} \;
実行結果
testdir/logs/app.log:error occurred
testdir/sample.txt:error message
testdir/src/main.txt:error found
仕組み
| 項目 | 内容 |
|---|---|
| grep -r | 指定ディレクトリ以下を再帰的に検索する |
| find | 条件に一致するファイルを検索する |
| -type f | 通常ファイルのみを対象にする |
| -exec | findの検索結果に対してコマンドを実行する |
| grep -H | 一致した行とファイル名を表示する |
| 組み合わせる利点 | ファイル種別や更新日時などの条件を付けてgrepを実行できる |
解説
grep -r はディレクトリ配下を手軽に再帰検索できます。
find と組み合わせることで対象ファイルを柔軟に絞り込みながら検索できるため、実運用ではこちらもよく利用されます。
grepの再帰的検索を高速化するコツ
ファイル作成
mkdir -p logs src vendor
ファイル作成
cat << 'LOG' > logs/app.log
Application started
LOG
ファイル作成
cat << 'LOG' > logs/error.log
Error: connection timeout
LOG
ファイル作成
cat << 'PY' > src/main.py
print("main application")
PY
ファイル作成
cat << 'PY' > src/utils.py
def helper():
pass
PY
ファイル作成
cat << 'JS' > vendor/lib.js
console.log("library");
JS
ファイル作成
cat << 'JS' > vendor/jquery.js
console.log("jquery");
JS
実行コマンド
grep -r --include="*.py" "main" .
実行結果
./src/main.py:print("main application")
実行コマンド
grep -r --exclude-dir=vendor "Error" .
実行結果
./logs/error.log:Error: connection timeout
実行コマンド
grep -r --exclude-dir=vendor "Application" .
実行結果
./logs/app.log:Application started
仕組み
| 項目 | 仕組み | 高速化の理由 |
|---|---|---|
| -r | ディレクトリ配下を再帰的に検索 | 手動でファイル指定する必要がない |
| --include="*.py" | 指定拡張子のみ検索 | 不要なファイルの読み込みを削減 |
| --exclude-dir=vendor | 指定ディレクトリを検索対象外にする | 大量のライブラリファイルを走査しない |
| 検索対象の絞り込み | 必要なファイルだけ探索 | ディスクI/Oと処理時間を削減 |
解説
grep の再帰的検索は便利ですが、検索対象を限定することで処理速度が大きく向上します。
特に vendor や node_modules のような大規模ディレクトリを除外するのが効果的です。
grepの再帰的検索のポイントまとめ
grepの再帰的検索は、ディレクトリ配下のファイルをまとめて検索できる便利な機能です。
基本構文を理解したうえで、ファイル名表示や行番号表示、正規表現の活用などを組み合わせることで検索効率を高められます。
grepの再帰的検索を使いこなすことで、日常的なログ解析やソースコード調査を効率化できるでしょう。
