Linux文本搜索之grep

grep命令

grep系列主要有grep,egrep(等同于grep -E),fgrep三种。

grep系列的命令都是按行处理的,也即搜索匹配的字符串,然后默认打印匹配的行到标准输出。

如 grep '^haibo' duplicate.txt: 输出所有以haibo开头的行。
haibod,please persisit and be patient whatever you may come across with.haibo
haibo,please persisit and be patient whatever you may come across with.
haibo ,please persisit and be patient whatever you may come across with.

grep选项:
- -c 打印匹配行的总行数;
- -n 打印出匹配行的行号和内容;
- -i 不区分大小写;
- -v 显示不匹配行的内容;

例子:

grep -c 'haibo' duplicat.txt

1:haibod,please persisit and be patient whatever you may come across with.haibo
2:haibo,please persisit and be patient whatever you may come across with.
7:haibo ,please persisit and be patient whatever you may come across with.

grep 和egrep(grep -E )的主要区别是grep支持基本正则表达式,egrep可支持扩展正则表达式。 因此首先要弄清楚基本正则表达式和扩展正则表达式。 可以阅读我之前写过的文章, 正则表达式
把正则表达式弄懂,弄懂,也就把grep,sed掌握了,因为正则表达式才是这些命令的精髓。简单例子:
grep -c '^$' duplicat.txt 该命令打印了文件中所包含的空行的行数。
命令: grep "^[^haibo]" duplicate.txt |uniq 输出所有以haibo开头的行。
DDDD
I love Python,and I'm confident on myself.

grep -e 'haibo|lina' duplicate.txt 该命令打印出了包含haibo或lina的行。 这里用到的就是扩展正则表达式。
也就是说,如用正则表达式匹配的话,还是最好直接用egrep,否则有些地方还需要用转义字符,比较麻烦。


grep允许使用国际模式的雷鸣进行匹配。(但说实话,我觉得还是用正则表达式看着方便。),下面是他们的对应关系。
[[:upper:]]--[A-Z] [[:lower:]] [a-z]
[[:digit:]] --[0-9] [[:alnum:]] [0-9a-zA-Z]
[[:alpha:]] --[a-zA-Z] [[:space:]] 空格键或TAB键。

例子: grep '[[:upper:]]' duplicate.txt |sort -u
DDDD
I love Python,and I'm confident on myself.

--------EOF---------
微信分享/微信扫码阅读