正则表达式
-c 计算匹配的行数
-o 只输出匹配出的字符串
-E egrep
-v 打印匹配之外的行
-l 从多文件中查找 输出含有表达式的文件名字
-L 与-l相反
-n 显示匹配的所在行
-R -r递归
-i 忽略pattern中的大小写
-q 静默 若grep 匹配成功返回0
- 要匹配给定文本中的所有单词, 可以使用下面的正则表达式
# 单词匹配 ?表示可能出现的空格 [a-zA-Z]单词
( ?[a-zA-Z]+ ?)
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}
或者
[[:digit:]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}

[clz@localhost shell_learn]$ echo -e "this is a word\nnext line" | grep word
this is a word
- grep命令只能解释match_text的一些特殊字符。如果要使用正则表达式,需要添加-E选项(使用扩展正则表达式)。或者也可使用默认允许正则表达式的grep命令—egrep
[clz@localhost shell_learn]$ echo this is a line. | egrep "[a-z]+\."
this is a line.
[clz@localhost shell_learn]$ echo this is a line. | egrep -o "[a-z]+\."
line.
egrep -c " ?[a-zA-Z]+ ?" cecho.sh
[clz@localhost shell_learn]$ echo -e "1 2 3 4\nhello\n5 6" | egrep -o "[0-9]"
1
2
3
4
5
6
[clz@localhost shell_learn]$ echo -e "1 2 3 4\nhello\n5 6" | egrep -o "[0-9]" |wc -l
6
[clz@localhost shell_learn]$ echo -e "1 2 3 4\nhello\n5 6" | egrep -b -o "[0-9]"
0:1
2:2
4:3
6:4
14:5
16:6
grep搜索中指定或排除文件
# 递归找出当前路径所有*.{c,cpp}文件下含有main的文件
grep "main()" . -r --include *.{c,cpp}
# 排除
grep "main()" . -r --exclude "README"
xargs && grep
- grep使用-z选项输出以0值字节作为字节作为终结符的文件名(\0) xargs -0 读取输入并用0值字节终结符分割文件名:
grep "test" file* -lZ | xargs -0 rm