grep(global search regular expression(RE) and print out the line缆镣,全面搜索正則表達式并把行打印出來)
是一種強大的文本搜索工具送淆,它能使用正則表達式搜索文本氛什,并把匹配的行打印出來旦签。
1. 常用用法
#在文件中搜索一個單詞,命令會返回一個包含“match_pattern”的文本行
grep match_pattern file
或者
grep "match_pattern" file
2. 在多個文件中查找
grep "match_pattern" file1 file2 file3 ...
3. 輸出除之外的所有行 -v 選項
grep -v "match_pattern" file
4. 標記匹配顏色 --color=auto 選項
grep "match_pattern" file_name --color=auto
5.只輸出文件中匹配到的部分 -o 選項
echo this is a test line. | grep -o -E "[a-z]+\."
輸出:line.
echo this is a test line. | egrep -o "[a-z]+\."
輸出:line.
6. 使用正則表達式 -E 選項
grep -E "[1-9]+"
或
egrep "[1-9]+"
7.統(tǒng)計文件或者文本中包含匹配字符串的行數(shù) -c 選項
grep -c "text" file
8.輸出包含匹配字符串的行號 -n 選項
grep -n "text" file
或
cat file_name | grep "text" -n
#多個文件
grep "text" -n file1 file2
9. 打印樣式匹配所位于的字符或字節(jié)偏移
echo gun is not unix | grep -b -o "not"
輸出:7:not
一行中字符串的字符偏移是從該行的第一個字符開始計算,起始值為0。選項 -b -o 一般總是配合使用
10. 搜索多個文件并查找匹配文本在哪些文件中
grep -l "text" file1 file2 file3...
#不在哪些文件中用大寫L
grep -L "text" file1 file2 file3...
#匹配多個文件不顯示文件名(大寫H顯示文件名)
grep -h "text" file1 file2 file3...
11. grep遞歸搜索文件 .標識當前目錄
grep "text" . -r -n
12. 忽略匹配樣式中的字符大小寫
echo "hello world" | grep -i "HELLO"
輸出:hello world
13. 選項 -e 制動多個匹配樣式
echo this is a text line | grep -e "is" -e "line" -o
輸出:
is
is
line
也可以使用-f選項來匹配多個樣式茴厉,在樣式文件中逐行寫出需要匹配的字符
cat patfile
aaa
bbb
echo aaa bbb ccc ddd eee | grep -f patfile -o
也可以用
echo this is a text line | grep -E "is|line" -o
14. 輸出開頭/結(jié)尾的行內(nèi)容
#找出A開頭的行內(nèi)容
cat file1 | grep ^A
#找出非A開頭的行內(nèi)容
cat file1 | grep ^[^A]
#找出A結(jié)尾的行內(nèi)容
cat file1 | grep A$
15. 打印出匹配文本之前或者之后的行
#顯示匹配某個結(jié)果之后的3行,使用 -A 選項:
seq 10 | grep "5" -A 3
輸出:
5
6
7
8
#顯示匹配某個結(jié)果之前的3行什荣,使用 -B 選項:
seq 10 | grep "5" -B 3
輸出:
2
3
4
5
#顯示匹配某個結(jié)果的前三行和后三行矾缓,使用 -C 選項:
seq 10 | grep "5" -C 3
輸出:
2
3
4
5
6
7
8
#如果匹配結(jié)果有多個,會用“--”作為各匹配結(jié)果之間的分隔符:
echo -e "a\nb\nc\na\nb\nc" | grep a -A 1
輸出:
a
b
--
a
b
喜歡的打賞支持哦 ^ ~ ^