一、用法
grep
全稱是Global Regular Expression Print
,表示使用正則表達(dá)式匹配文本。
命令格式:grep pattern file
-
-c
:輸出匹配到的數(shù)量。 -
-i
:不區(qū)分大小寫。 -
-h
:不顯示文件名慷妙。 -
-n
:顯示匹配行和行號。 -
-b
:顯示匹配到的字符串偏移允悦。 -
-o
:只輸出匹配到的內(nèi)容膝擂,一般與-b
一起使用。 -
-v
:反向輸出隙弛,輸出所有不匹配的行架馋。
二、示例
測試文件
> cat test.txt
HelloWorld.
I'm maqian.
This is guangzhou.
Today is so hot.
But i still have a fever!
示例
> grep maqian test.txt
I'm maqian.
> grep maqian * # 通配符匹配會顯示文件名
test.txt:I'm maqian.
> grep maqian * -h # 不顯示文件名
I'm maqian.
> grep maqian * -c # 統(tǒng)計次數(shù)
1
> grep i * -c
4
> grep i * -h # 查詢包含i的行
I'm maqian.
This is guangzhou.
Today is so hot.
But i still have a fever!
> grep i * -n # 結(jié)果顯示行號
2:I'm maqian.
3:This is guangzhou.
4:Today is so hot.
5:But i still have a fever!
> grep i * -o # 只顯示匹配到的內(nèi)容
i
i
i
i
i
i
> grep i * -ob # ob一起使用顯示匹配到的內(nèi)容在文件中的偏移
19:i
26:i
29:i
49:i
64:i
68:i
> grep i * v # 反向查找全闷,找出所有不匹配的行
test.txt:I'm maqian.
test.txt:This is guangzhou.
test.txt:Today is so hot.
test.txt:But i still have a fever!
grep: v: No such file or directory
> grep i * -v
HelloWorld.
正則表達(dá)式示例:
復(fù)制上面的命令和輸出到test2.txt
> grep -E "\[.*\]" test2.txt # 匹配所有類似[***]的行
# 以下全為輸出
[root@localhost grep]# grep maqian test.txt
[root@localhost grep]# grep maqian * # 通配符匹配會顯示文件名
[root@localhost grep]# grep maqian * -h # 不顯示文件名
[root@localhost grep]# grep maqian * -c # 統(tǒng)計次數(shù)
[root@localhost grep]# grep i * -c
[root@localhost grep]# grep i * -h # 查詢包含i的行
[root@localhost grep]# grep i * -n # 結(jié)果顯示行號
[root@localhost grep]# grep i * -o # 只顯示匹配到的內(nèi)容
[root@localhost grep]# grep i * -ob # ob一起使用顯示匹配到的內(nèi)容在文件中的偏移
[root@localhost grep]# grep i * v # 反向查找叉寂,找出所有不匹配的行
[root@localhost grep]# grep i * -v