0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

grep コマンドの使い方をサンプル付きでわかりやすく解説

0
Last updated at Posted at 2018-05-23

🔍 grepとは?

grep は「Global Regular Expression Print」の略で、文字列検索ツールです。
ある文字列を含む行をファイルや標準入力から探して表示してくれます。


✅ 基本構文

grep [オプション] 検索文字列 ファイル名

📘 基本的な使い方

1. ファイル内で文字列を検索する

grep "Hello" sample.txt

sample.txt の中から "Hello" を含む行を表示します。


2. 大文字・小文字を無視して検索(-i)

grep -i "hello" sample.txt

"Hello", "HELLO", "heLLo" など、大文字小文字を区別せずにマッチします。


3. 行番号を表示する(-n)

grep -n "error" log.txt

"error" を含む行と、その行番号を表示します。


4. 再帰的に検索(-r または -R)

grep -r "TODO" ./src

ディレクトリ ./src 以下の全ファイルから "TODO" を検索します。


5. 正規表現で検索(デフォルトで正規表現対応)

grep "error[0-9]" log.txt

"error" の後に数字が1桁続くパターン(例: error1, error5)を検索します。


6. 該当しない行を表示する(-v)

grep -v "DEBUG" log.txt

"DEBUG" を含まない行を表示します。


7. 一致した箇所だけを表示(-o)

grep -o "https://[^ ]*" urls.txt

ファイル内のURL部分だけを抽出します。


8. 複数ファイルで検索(ワイルドカード)

grep "main()" *.c

カレントディレクトリの .c ファイルすべてに対して "main()" を検索します。


🧪 応用例:パイプと組み合わせる

例: ps コマンドと組み合わせて特定のプロセスを探す

ps aux | grep "nginx"

実行中のプロセスの中から "nginx" を含むものを表示します。


例: ログファイルからエラー行だけを抽出

cat server.log | grep -i "error" | grep -v "404"

"error" を含むが、"404" を含まないログ行を抽出します。


🎯 まとめ

オプション 説明
-i 大文字小文字を無視して検索
-n 行番号を表示
-v 一致しない行を表示
-r / -R ディレクトリを再帰的に検索
-o 一致した文字列のみ表示
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?