【linux shell】grep 常用选项
发布时间:2020-12-15 16:32:56 所属栏目:安全 来源:网络整理
导读:color选项增加颜色渲染 使用拓展正则表达式 如果要使用正则表达式,需要添加-E选项——这意味着使用扩展(extended)正则表达式。或者也可以使用默认允许正则表达式的grep命令——egrep。例如: $ grep - E "[a-z]+" filename #或者 $ egrep "[a-z]+" filena
color选项增加颜色渲染使用拓展正则表达式如果要使用正则表达式,需要添加-E选项——这意味着使用扩展(extended)正则表达式。或者也可以使用默认允许正则表达式的grep命令——egrep。例如: $ grep -E "[a-z]+" filename
#或者
$ egrep "[a-z]+" filename
仅输出匹配结果使用 [root@CentOS ~]# grep word readme
this is the line containing word
[root@CentOS ~]# grep word readme -o
word
翻转匹配
[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
输出匹配文件
[root@CentOS ~]# grep -l word readme out.html
readme
输出行号
字节偏移
-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.
[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.
递归搜索文件
[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");
忽略大小写
[edemon@CentOS tmp]$ echo "HAha" |grep -i "haha"
HAha
多模式匹配使用 [edemon@CentOS tmp]$ echo this is a line |grep -e "is" -e "line" -o
is
is
line
使用文件 [edemon@CentOS tmp]$ echo -e "isnline" > 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
搜索时包括文件或排除文件
[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
排除目录: 静默输出
[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
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |