顯示不以#開頭的行
> grep ^[^#] rumenz.txt
顯示#開頭的行
> grep ^# rumenz.txt
從單個(gè)文件查找指定字符串
> grep "rumenz" 1.txt
從多個(gè)文件查找指定字符串
> grep "rumenz" *.html
忽略大小寫, 并顯示行號(hào)
> grep -in "rumenz" 1.txt
顯示查找到的總行數(shù)
> grep -c "rumenz" 1.txt
查找目錄下所有文件,并只輸出含有該文本的文件名
> grep -l "rumenz" *
-l: 查詢多文件的時(shí)候只輸出包含匹配字符的文件名
遞歸查找目錄下所有文件,并只輸出含有該文本的文件路徑
> grep -rl "rumenz" .
grep靜默輸出
不會(huì)輸出任何信息,如果命令運(yùn)行成功返回0,失敗則返回非0值。一般用于條件測(cè)試。
> grep -q "rumenz" 1.txt
除開某一個(gè)目錄不匹配
> grep -R --exclude-dir="tmp" "rumenz"
tmp 中的文件不用查找
去掉文本中的空行
> cat 1.txt | grep -v "^s*$"
過濾注釋行
> cat 1.txt | grep -v "^#"
同時(shí)過濾空白行與注釋行
> cat 1.txt | grep -v "^$" | grep -v "^#"
打印匹配行的后5行
> grep -A 5 'rumenz' 1.txt
打印匹配行的前5行
> grep -B 5 'rumenz' 1.txt
打印匹配行的前后5行
> grep -C 5 'rumenz' 1.txt
模糊匹配
> grep "abc" 1.txt //結(jié)果為abcd, abcde, abc等
精確匹配
> grep -w "abc" 1.txt
同時(shí)匹配多個(gè)字符串
> cat 1.txt | grep -e "ab" -e "ef" -o
- -e 指定字符串作為查找文件內(nèi)容的關(guān)鍵字符
- -o 只輸出文件中匹配到的部分, 不會(huì)打印多余的內(nèi)容。
只在目錄中所有的.php和.html文件中遞歸搜索字符"rumenz"
> grep -r "rumenz" --include *.{html,php}
在搜索結(jié)果中排除所有README文件
> grep -r "rumenz" --exclude "README" .
在搜索結(jié)果中排除filelist文件列表里的文件
> cat filelist
aaa
bbb
rumenz
> grep -r "rumenz" --exclude-from filelist .
原文鏈接
:https://rumenz.com/rumenbiji/linux-grep-skills.html