siwen

siwen

😉

grep 命令

grep 文本過濾工具#

說明:

grep(全面搜索正則表達式並打印出匹配的行)是一種強大的文本搜索工具,它能使用正則表達式搜索文本,並將匹配的行打印出來。用於過濾搜索的特定字符。可使用正則表達式,能多種命令配合使用,使用上十分靈活。

語法:

grep [選項...] 模式 [文件...]
grep [選項...] -e 模式... [文件...]
grep [選項...] -f 模式文件... [文件...]

grep 命令選項#

選項作用
-c統計文件中匹配的行數
-i忽略模式中的字母大小寫
-n列出所有的匹配行,並顯示行號
-v列出沒有匹配模式的行,取反
-e多個選項間的邏輯或
-o只顯示被模式匹配到內容
-l列出帶有匹配內容的文件名
-w匹配整個單詞
-q靜默模式,不輸出任何信息
-r遞歸搜索
-f根據文件內容匹配多個(文件中逐行寫出要匹配的內容)
-Aafter, 後 n 行(被匹配到的行及後 n 行)
-Bbefore, 前 n 行(被匹配到的行及前 n 行)
-Ccontext,前後各 n 行(被匹配到的行及前後各 n 行)
-E使用擴展的正則表達式,相當於 egrep
-F相當於 fgrep,不支持正則表達式
-P使用 perl 正則表達式

使用幫助命令可查看全部選項(grep --help 或 man grep)

  • grep 使用 “標準正則表達式” 作為匹配標準
  • egrep 擴展的 grep 命令,相當於 grep -E ,使用擴展正則表達式作為匹配標準
  • fgrep 簡化版的 grep 命令,不支持正則表達式,但搜索速度快,系統資源使用率低

示例#

# 統計空行的行數
[root@localhost ~]# grep -c '^$' test.txt

# 包含字符h的行(不區分大小寫)
[root@localhost ~]# grep -i 'h' test.txt

# 列出所有空行 並顯示行號
[root@localhost ~]# grep -n '^$' test.txt

# 列出所有非空行
[root@localhost ~]# grep -v '^$' test.txt

# 列出所有以S開頭的行和空行
[root@localhost ~]# grep -e '^$' -e '^S' test.txt 

# 過濾所有的數字 只顯示被匹配到的內容
[root@localhost ~]# grep -o '[0-9]' test.txt 

# 列出內容包含a的文件名
[root@localhost ~]# grep -l 'a' demo.txt test.txt pwd.txt

# 匹配包含單詞you的行
[root@localhost ~]# grep -w 'you' test.txt 

# 根據file裡面的範文進行匹配
[root@localhost ~]# grep -f file test.txt 

# 列出包含can的行以及其後三行 
[root@localhost ~]# grep -A3 'can' test.txt  

# 列出包含can的行以及其前三行 
[root@localhost ~]# grep -B3 'can' test.txt  

# 列出包含can的行以及其前後各三行 
[root@localhost ~]# grep -C3 'can' test.txt  

# 重複d字符最少2次
[root@localhost ~]# grep -E 'd{2,}' test.txt
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。