一、用法

grep全称是Global Regular Expression Print,表示使用正则表达式匹配文本。

命令格式:grep pattern file

  • -c:输出匹配到的数量。
  • -i:不区分大小写。
  • -h:不显示文件名。
  • -n:显示匹配行和行号。
  • -b:显示匹配到的字符串偏移。
  • -o:只输出匹配到的内容,一般与-b一起使用。
  • -v:反向输出,输出所有不匹配的行。
  • -E:正则匹配。

二、示例

测试文件

> 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  # 统计次数
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  # 结果显示行号
2:I''m maqian.
3:This is guangzhou.
4:Today is so hot.
5:But i still have a fever!
> grep i * -o  # 只显示匹配到的内容
i
i
i
i
i
i
> grep i * -ob  # ob一起使用显示匹配到的内容在文件中的偏移
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.

正则表达式示例:

复制上面的命令和输出到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  # 统计次数
[root@localhost grep]# grep i * -c
[root@localhost grep]# grep i * -h  # 查询包含i的行
[root@localhost grep]# grep i * -n  # 结果显示行号
[root@localhost grep]# grep i * -o  # 只显示匹配到的内容
[root@localhost grep]# grep i * -ob  # ob一起使用显示匹配到的内容在文件中的偏移
[root@localhost grep]# grep i * v  # 反向查找,找出所有不匹配的行
[root@localhost grep]# grep i * -v
最后修改:2018 年 01 月 04 日
如果觉得我的文章对你有用,请随意赞赏