作為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