shell grep文本搜索


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 *.{txt,cpp}
(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"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM