【linux shell】grep 常用选项

前端之家收集整理的这篇文章主要介绍了【linux shell】grep 常用选项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

color选项增加颜色渲染

使用拓展正则表达式

如果要使用正则表达式,需要添加-E选项——这意味着使用扩展(extended)正则表达式。或者也可以使用默认允许正则表达式的grep命令——egrep。例如:

$ grep -E "[a-z]+" filename 
#或者 
$ egrep "[a-z]+" filename

输出匹配结果

使用 -o

[root@CentOS ~]# grep word readme
this is the line containing word
[root@CentOS ~]# grep word readme -o
word

翻转匹配

-v,--invert-match翻转匹配即是将不属于模式的内容输出

[root@CentOS ~]# grep -v word readme 
this is a simple line.

输出匹配行或者匹配项个数

[root@CentOS ~]# cat readme
this is the line containing word,word
this is a simple line.

[root@CentOS ~]# grep -c word readme 
1
[root@CentOS ~]# grep -o word readme |wc -l
2

输出匹配文件

-l

[root@CentOS ~]# grep -l word readme out.html 
readme

输出行号

-n

字节偏移

-b

-b,--byte-offset
              Print  the 0-based byte offset within the input file before each line of output.  If -o (--only-matching) is specified,print the offset
              of the matching part itself.

-o输出匹配单词结果

[root@CentOS ~]# grep -b -o word readme 
28:word
34:word
39:word
[root@CentOS ~]# cat readme
this is the line containing word,word
word
this is a simple line.

递归搜索文件

-R

[edemon@CentOS tmp]$ grep "open" . -R 
./write.c:  int fd = open("./tmp.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
./write.c:      perror("tmp.txt open wrongly");

忽略大小写

-i

[edemon@CentOS tmp]$ echo "HAha" |grep -i "haha"
HAha

多模式匹配

使用-e选项

[edemon@CentOS tmp]$ echo this is a line |grep -e "is" -e "line" -o
is
is
line

使用文件

[edemon@CentOS tmp]$ echo -e "is\nline" > pattern_txt
[edemon@CentOS tmp]$ cat pattern_txt 
is
line

[edemon@CentOS tmp]$ echo this is a line |grep -f pattern_txt -o
is
is
line

搜索包括文件或排除文件

includeexclude

[edemon@CentOS tmp]$ grep "open" . -r --include *.c
./write.c:  int fd = open("./tmp.txt",0644);
./write.c:      perror("tmp.txt open wrongly");
[edemon@CentOS tmp]$ grep "open" . -r --exclude *.c

排除目录:--exclude-dir
文件中读取所需排除的文件列表: --exclude-from FILE

静默输出

-q选项可以使得grep不输出任何东西到stdout。即使出现出错。
当返回值是0时,则找到了对象。非0则没找到。

[edemon@CentOS workspace]$ cat auto.c |grep -q longjmp
[edemon@CentOS workspace]$ echo $?
0

匹配文本上下文输出

#输出4后面2行
[edemon@CentOS workspace]$ seq 10 |grep 4 -A 2
4
5
6
#输出4前面2行
[edemon@CentOS workspace]$ seq 10 |grep 4 -B 2
2
3
4
#输出4前后两行
[edemon@CentOS workspace]$ seq 10 |grep 4 -C 2
2
3
4
5
6

猜你在找的Bash相关文章