首頁·終端機命令

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