Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

每天一個 Linux 命令(34):grep 文本搜索全攻略

grep 全名是 global search regular expression(RE) and print out the line,也就是「全面搜尋正則表達式並把符合的行印出來」。它是 Linux 最強大的文本搜尋工具,能搭配正則表達式精準定位內容。

基本用法

grep [選項]... PATTERN [FILE]...

功能是在每個 FILE 或標準輸入中查找 PATTERN。

常用選項

  • -V, --version:顯示版本號
  • -i:比對時忽略大小寫
  • -v, --invert-match:反向選擇,印出不匹配的行
  • -f FILE:以檔案中每行字串作為比對樣式
  • -c:統計符合的行數
  • -n:輸出時一併印出行號
  • -o:只印出符合 PATTERN 的部分
  • -E:使用延伸正則表達式(ERE)
  • -q:靜默模式,常用於腳本判斷
  • --color=auto:以顏色標記命中內容

實作範例

先準備三個測試檔案 t1.txt、t2.txt、t3.txt。

1. 在多個檔案中搜尋字串

[root@localhost grepDir]# grep "MenAngel" t1.txt t2.txt t3.txt
t1.txt:I'm MenAngel!

2. 反向輸出

[root@localhost grepDir]# grep -v "MenAngel" t1.txt t2.txt t3.txt

會印出所有「不含」MenAngel 的行。

3. 標色命中

[root@localhost grepDir]# grep "fight" t1.txt t2.txt t3.txt --color=auto
t2.txt:Every one fights for a better future,but I fight for freedom!

4. 統計行數

[root@localhost grepDir]# grep -c "that" t1.txt t2.txt t3.txt
t1.txt:1
t2.txt:0
t3.txt:2

5. 顯示行號

[root@localhost grepDir]# grep -n "that" t1.txt t2.txt t3.txt

6. 搭配管道

[root@localhost grepDir]# cat t1.txt t2.txt t3.txt | grep "MenAngel"
I'm MenAngel!

7. 以指定字元開頭

[root@localhost grepDir]# cat t1.txt t2.txt t3.txt | grep ^I
I'm MenAngel!

8. 不以指定字元開頭

[root@localhost grepDir]# cat t1.txt t2.txt t3.txt | grep ^[^I]

9. 上下文(-A / -B / -C)

[root@localhost grepDir]# seq 10 | grep "5" -A 3
5
6
7
8
[root@localhost grepDir]# seq 10 | grep "5" -B 3
2
3
4
5
[root@localhost grepDir]# seq 10 | grep "5" -C 3
2
3
4
5
6
7
8

多段命中時,各段之間會以 -- 作為分隔符。

10. 多樣式比對

[root@localhost grepDir]# echo this is a text line | grep -e "is" -e "line" -o
is
is
line

11. 從檔案讀取樣式

[root@localhost grepDir]# echo MenAngel is sunjimeng | grep -f patfile
MenAngel is sunjimeng

其他值得記的參數

-r 遞迴搜尋目錄、-l 只印符合的檔名、-L 只印不符合的檔名、-w 全字比對、-x 整行完全匹配、-m NUM 命中指定次數後停止。另外 egrep 等同 grep -E,fgrep 等同 grep -F。

若 FILE 為 - 則讀取標準輸入;不帶 FILE 時讀取當前目錄(需搭配 -r)。有任何一行命中,退出碼為 0,否則為 1;發生錯誤且未指定 -q 時退出碼為 2,這在寫腳本判斷時很好用。

grep 的用法遠不止於此,累積更多實務經驗後再回來補充。

Copyright © Linux教程網 All Rights Reserved