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