一、Regexp selection and interpretation:
-i, --ignore-case 不区分大小写 ignore case distinctions
-P, --perl-regexp 作为Perl正则匹配 PATTERN is a Perl regular expression
二、Miscellaneous:
-s, --no-messages 不显示错误信息 suppress error messages
-v, --invert-match 反向匹配,即显示不匹配的行 select non-matching lines
-V, --version 打印版本信息并退出 print version information and exitv
三、Output control:
-c, --count 只输出匹配行的数目 print only a count of matching lines per FILE
-n, 显示匹配行以及行号 --line-number print line number with output lines
--line-buffered flush output on every line
-l, 查询多文件的时候只输出包含匹配字符的文件名--files-with-matches print only names of FILEs containing matches
-h, 查询的时候不适用文件名--no-filename suppress the prefixing filename on output
--label=LABEL print LABEL as filename for standard input
-o, 只显示匹配行中匹配正则表达式的那部分 --only-matching show only the part of a line matching PATTERN
四、Context control:
-B n 前n行,B记忆为(Before) --before-context=NUM print NUM lines of leading context
-A n 后n行,A记忆为(After) --after-context=NUM print NUM lines of trailing context
-C, n 前n行,后n行,C记忆为(Center) --context=NUM print NUM lines of output context
五、部分正则表达式
\ 反义字符
^ 开始
$结束
[] 单个字符,[A]
[ - ] 匹配一个范围,[0-9a-zA-Z]匹配所有数字和字母
* 前面的字符出现0次或者多次
+ 前面的字符出现了一次或者多次
. 任意字符
举例
1.-A -B -C 匹配行的上下文
cat 1.txt | grep -C 3 "j"
ifconfig | grep -A 2 "匹配的关键字" 显示的是所有匹配行和它下面的两行
ifconfig | grep -C 3 "匹配的关键字" 显示的是所有匹配行和它上下面的三行
2.-cn或-c 统计
grep -cn "*.df.*" 文件名 显示统计符合关键字的行数
3.--color 查询关键字并高亮显示
grep "关键字" --color 文件名文件名
4. -r 递归查找当前目录及子目录下面包含匹配字符的文件内容
grep -nr "关键字" --color 目录名/或 .表示是在当前目录下
grep -nr "关键字" --color 文件名 会显示有行号
5.-l 查找子目录 匹配后只输出有该关键字的文件名
grep -lr "关键字" 目录名
6.查找邮箱
grep -oP "[a-zA-Z0-9_-]+@[a-zA-Z0-9]+(\.[a-zA-Z0-9_-]+)+" 文件名