shell編程系列8--文本處理三劍客之grep和egrep

grep和egrep

第一種形式:grep [option] [pattern] [file1,file2...]

第二種形式:command | grep [option] [pattern]

grep參數

選項    含義
-v    不顯示匹配行信息
-i    搜索時忽略大小寫
-n    顯示行號
-r    遞歸搜索
-E    支持擴展正則表達式
-F    不按正則表達式匹配,按照字符串字面意思匹配
不經常使用選項
-c 只顯示匹配行總數 -w 匹配整詞 -x 匹配整行 -l 只顯示文件名,不顯示內容 -s 不顯示錯誤信息
grep和egrep: grep語法格式
grep [option] [pattern] [file1,file2...] 必須掌握的選項: -v 顯示不匹配pattern的行 -i 搜索時忽略大小寫 -n 顯示行號 -E 支持擴展的正則表達式 -F 不支持正則表達式,按字符串的字面意思進行匹配 -r 遞歸搜索 須要瞭解的選項: -c 只輸出匹配行的數量,不顯示具體內容 -w 匹配整詞 -x 匹配整行 -l 只累出匹配的文件名,不顯示具體匹配行內容 grep和egrep: grep默認不支持擴展正則表達式,只支持基礎正則表達式 使用grep -E能夠支持擴展正則表達式 使用egrep能夠支持擴展正則表達式,與grep -E等價 # 示例 # 顯示file中有python的行 [root@es01 ~]# cat file i love python hello python aaa bbb I LOVE PYTHON HELLO PYTHON PYTHON IS A AI LANGUAGE end [root@es01 ~]# grep python file i love python hello python # 沒有python的行,不忽略大小寫 [root@es01 ~]# grep -v python file aaa bbb I LOVE PYTHON HELLO PYTHON PYTHON IS A AI LANGUAGE end # 沒有python的行,忽略大小寫 [root@es01 ~]# grep -vi python file aaa bbb end # 查找/etc/man_db.conf 中帶man的行,在文件中的行號 [root@es01 ~]# grep -n man /etc/man_db.conf 3:# This file is used by the man-db package to configure the man and cat paths. 4:# It is also used to provide a manpath for those without one by examining 5:# their PATH environment variable. For details see the manpath(5) man page. 12:# MANDATORY_MANPATH manpath_element 13:# MANPATH_MAP path_element manpath_element 14:# MANDB_MAP global_manpath [relative_catpath] 18:#MANDATORY_MANPATH /usr/src/pvm3/man 20:MANDATORY_MANPATH /usr/man 21:MANDATORY_MANPATH /usr/share/man 22:MANDATORY_MANPATH /usr/local/share/man 25:# ie. what man tree holds man pages for what binary directory. 29:MANPATH_MAP /bin /usr/share/man 30:MANPATH_MAP /usr/bin /usr/share/man 31:MANPATH_MAP /sbin /usr/share/man 32:MANPATH_MAP /usr/sbin /usr/share/man 33:MANPATH_MAP /usr/local/bin /usr/local/man 34:MANPATH_MAP /usr/local/bin /usr/local/share/man 35:MANPATH_MAP /usr/local/sbin /usr/local/man 36:MANPATH_MAP /usr/local/sbin /usr/local/share/man 37:MANPATH_MAP /usr/X11R6/bin /usr/X11R6/man 38:MANPATH_MAP /usr/bin/X11 /usr/X11R6/man 39:MANPATH_MAP /usr/games /usr/share/man 40:MANPATH_MAP /opt/bin /opt/man 41:MANPATH_MAP /opt/sbin /opt/man ... # -E 支持擴展正則表達式選項 [root@es01 ~]# cat file i love python hello python aaa bbb I LOVE PYTHON HELLO PYTHON PYTHON IS A AI LANGUAGE end [root@es01 ~]# grep "python|PYTHON" file [root@es01 ~]# grep -E "python|PYTHON" file i love python hello python I LOVE PYTHON HELLO PYTHON PYTHON IS A AI LANGUAGE [root@es01 ~]# # 只顯示匹配到的行數 [root@es01 ~]# grep -c python file 2 [root@es01 ~]# grep -c man /etc/man_db.conf 44 # 匹配python或者PYTHON [root@es01 ~]# grep -E "python|PYTHON" file i love python very hello python I LOVE PYTHON HELLO PYTHON PYTHON IS A AI LANGUAGE lovelove python [root@es01 ~]# egrep "python|PYTHON" file i love python very hello python I LOVE PYTHON HELLO PYTHON PYTHON IS A AI LANGUAGE lovelove python
相關文章
相關標籤/搜索