shell grep文字搜尋

2022-07-15 19:15:09 字數 1601 閱讀 8851

grep語法:

grep [option] "string_to_find" filename

選項與引數:

(1)-i:忽略搜尋字串的大小寫

(2)-v:取反,即輸出不匹配的那些文字行

(3)-n:輸出行號

(4)-l:輸出能夠匹配模式的檔名,相反的選項為-l

(5)-q:靜默輸出

(6)-w:精準匹配

根據實際需求進行選擇即可

string_to_find為需要匹配的模式,可以填寫字串或者正規表示式

filename為需要查詢的檔案的名稱

現有檔案test_001.txt,檔案內容如下:

yello

hello,hello

hello,hello

hello,hello

hello,hello

hello,hello

hello world

1.統計檔案中能夠匹配的行數

grep -c "hello" test_001.txt

結果:6

2.統計檔案中匹配的數量

grep -o "hello" test_001.txt | wc -l

結果:11

3.遞迴搜尋

-r:grep的引數filename為目錄時可以加上本選項表示遞迴搜尋

列如:檔案test_001.txt的上一層目錄為:sj_add

grep -r "hello" sj_add

結果:sj_add/test_001.txt:hello,hello

sj_add/test_001.txt:hello,hello

sj_add/test_001.txt:hello,hello

sj_add/test_001.txt:hello,hello

sj_add/test_001.txt:hello,hello

sj_add/test_001.txt:hello world

4.匹配多個正規表示式:-e:該選項加上正規表示式就是乙個需要匹配的模式

找出匹配hello或者world的行

grep -e "hello" -e "world" test_001.txt

結果:hello,hello

hello,hello

hello,hello

hello,hello

hello,hello

hello world

5.指定/排除檔案

--include:指定需要搜尋的檔案

--exclude:排除需要搜尋的檔案

--exclude-dir:排除需要搜尋的目錄

例子:(1)搜尋sj_add目錄中.txt和.cpp檔案中的含有yello的行:

grep -r "yello" ./sj_add --include *.

(2)搜尋sj_add目錄中含有yello的行,但不搜尋readme檔案:

grep -r "yello" ./sj_add --exclude "readme"

(3)搜尋sj_add目錄中含有yello的行,但不搜尋.git資料夾:

grep -r "yello" ./sj_add --exclude-dir ".git"

SHELL grep搜尋文字

1 grep pattern filename 2 從stdin中讀取 root master1 test echo e this is a word nnext line grep word this is a word 3 單個grep對多個檔案進行搜尋 grep match text file...

shell grep字元查詢,新增命令

例項一 在當前目錄下test.html中查詢以 pdf 結尾的行,並將結果輸出到test.txt檔案中 more test.html grep pdf test.txt 例項二 參考 1 顯示當前目錄下test.txt所有行 2 顯示test.txt中以 c 開頭的行 more test.txt g...

shell grep命令及常見用法

背景 grep的全稱是global regular expression print,是linux中最強大的文字搜尋命令之一,常用於搜尋文字檔案中是否含有某些特定模式的字串。該命令以行為單位讀取文字並使用正規表示式進行匹配,匹配成功後列印出該行文字。命令格式 grep option string t...