二、grep文字搜尋工具
阿新 • • 發佈:2021-08-22
grep命令作為Unix中用於文字搜尋的神奇工具,能夠接受正則表示式,生成各種格式的輸出。除此外,它還有大量有趣的選項。
# 搜尋包含特定模式的文字行: [root@centos8 ~]#grep pattern filename # 可以從stdin中讀取: [root@centos8 ~]#echo -e "this is a word\nnext line" | grep word this is a word # 單個grep命令也可以對多個檔案進行搜尋: [root@centos8 ~]#grep "a_txt" file1,file2,file3 ... # 用--color選項可以在輸出行中著重標記出匹配到的單詞: [root@centos8 ~]#grep word a.txt --color=auto nihoa word hell okd old edu # grep命令只解釋match_txt中的某些特殊字元。如果要使用正則表示式,需要新增-E選項————這意味著使用擴充套件正則表示式。或者也可以使用預設允許正則表示式的grep命令————egrep。 [root@centos8 ~]#grep -E "[a-z]+" filename [root@centos8 ~]#egrep "[a-z]+" filename # 使用選項-o 可以只輸出文件中匹配到的文字部分: [root@centos8 ~]#echo this is a line. | egrep -o "[a-z]+\." line. # 不加 o 的輸出結果 [root@centos8 ~]#echo this is a line. | egrep "[a-z]+\." this is a line. # 選項 -v 要列印除包含match_txt行之外的所有行: [root@centos8 ~]#grep -v math_txt filename # 選項 -c 統計檔案或文字中包含匹配字串的行數: [root@centos8 ~]#grep -c "word" a.txt # 注意:-c 只是統計匹配行的數量,並不是匹配的次數,例如: [root@centos8 ~]#echo -e "1 2 3 4\nhello\n5 6" > a.txt [root@centos8 ~]#cat a.txt 1 2 3 4 hello 5 6 [root@centos8 ~]#egrep -c "[0-9]" a.txt 2 # 搜尋多個檔案並找出匹配文字位於哪一個檔案中: [root@centos8 ~]#grep -l linux a.txt b.txt a.txt b.txt 和-l 相反的選項是-L,它會返回一個不匹配的檔案列表