grep
テキスト処理
書き方
grep -rn '[pattern]' [path]文の中から模様に合う行を抜き出します。既定が基本正規表現なので、+ ? | と () は -E かバックスラッシュが要ります。
よく使うオプション
| オプション | 意味 |
|---|---|
| -i | Ignore case |
| -r | Search a whole directory tree; -R also follows symlinks |
| -n | Print the line number of each hit |
| -v | Invert: print the lines that do not match |
| -l | Print only the names of the files that matched |
| -w | Match whole words only |
| -E | Extended regex, so + ? | and () work unescaped |
| -C | Print N lines of context around each hit |
例
grep -rn 'TODO' src/Every TODO in the tree, with file and line.
grep -v '^#' nginx.confDrops 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