作为linux中最为诶常用的三大文本(awk,sed,grep),掌握好期用法还是很有必要的。

首先谈一下grep常用的常用格式为:grep [选项] [文本] [文件]

grep家族一共有三个:grep,egrep,fgrep。

常用选项:

  -E:开启扩展(Extend) 的正则表达式。

  -i:忽略大小写(ignoew case)。、

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -i "Root" /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

  -v:反过来(invert),只打印没有匹配的,不匹配的不打印。

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -v "root" /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

  -n:显示行号。

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -n "root" /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
10:operator:x:11:0:operator:/root:/sbin/nologin

  -w:被匹配的文本只能是单词,而不能是单词中的某一部分,如文本中有liker,而我搜寻的只是like,就可以使用-w选项来避免匹配liker。

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -w "root" /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

  -c:显示总共有多少行被匹配到了,而不是显示被匹配到的内容,注意如果同时使用-vc选项显示有多少行没有被匹配到。

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -c "root" /etc/passwd
2

  -o:只显示被模式匹配到的字符串。

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -o "root" /etc/passwd
root
root
root
root

  --color:将匹配到的内容以颜色高亮显示。

  -A n:显示匹配到的字符串所在的行及其后n行,A=after

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -A 2 "core id" /proc/cpuinfo 
core id        : 0
cpu cores    : 1
apicid        : 0

  -B n:显示匹配到的字符串所在的行及其前n行,B=before

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -B 2 "core id" /proc/cpuinfo 
physical id    : 0
siblings    : 1
core id        : 0

  -C n:显示匹配到的字符串所在的行及其前后各n行,C=context

[zhanzhuang@alibabaCentos7 guideAutomation]$ grep -C 2 "core id" /proc/cpuinfo 
physical id    : 0
siblings    : 1
core id        : 0
cpu cores    : 1
apicid        : 0
posted on 2019-01-16 10:31  帅过驴的袋鼠  阅读(1077)  评论(0编辑  收藏  举报