grep

テキスト処理

書き方

grep -rn '[pattern]' [path]

文の中から模様に合う行を抜き出します。既定が基本正規表現なので、+ ? | と () は -E かバックスラッシュが要ります。

よく使うオプション

オプション意味
-iIgnore case
-rSearch a whole directory tree; -R also follows symlinks
-nPrint the line number of each hit
-vInvert: print the lines that do not match
-lPrint only the names of the files that matched
-wMatch whole words only
-EExtended regex, so + ? | and () work unescaped
-CPrint N lines of context around each hit

grep -rn 'TODO' src/

Every TODO in the tree, with file and line.

grep -v '^#' nginx.conf

Drops the comment lines.

ps aux | grep '[n]ginx'

Finds nginx without matching the grep itself.

パイプでつないで使うのが本来の形です。ひとつで全部やるより、三つつないだ方が短くなります。

読み方

  • 角括弧 [ ] は省いてよい部分です。
  • 三点 … は複数並べられるという意味です。
  • オプションは大文字小文字を区別します — -r と -R が別物のコマンドもあります。

よくある質問

Q. grep は何をしますか。

文の中から模様に合う行を抜き出します。既定が基本正規表現なので、+ ? | と () は -E かバックスラッシュが要ります。

Q. どう打ちますか。

grep -rn '[pattern]' [path] — 角括弧は省いてよい部分です。

Q. よく使うオプションはいくつですか。

ここにまとめたのは8個です。全部は man grep にあります。このコマンドはテキスト処理の仲間です。

関連するコマンド

man ページ: man grep