linux 系统 grep 命令

1、利用vim编辑器创建测试文件

[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r

 

 

2、提取特定行

  最简单的用法,提取包含特定字符串的行,例如提取包含字符串k的行:

[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep 'k' a.txt
s y k m
e t k r

 

 加-n 参数,在匹配的行前面加上行号,例如提取包含k的行并加上行号:

[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep -n 'k' a.txt
2:s y k m
5:e t k r

 

-v 参数用反向匹配,提取不包含特定字符串的行,例如提取不包含k的行:

[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep -v 'k' a.txt
e d 4 9
2 r t s
w d g h

 

加^符号用于提取以特定字符开头的行,例如提取以e开头的行:

[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep '^e' a.txt
e d 4 9
e t k r

 

加$符号用于提取以特定字符串结尾的行,例如提取以s结尾的行:

 

[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep 's$' a.txt
2 r t s

 

 

加 -i参数用于忽略大小写:

[root@linuxprobe test]# cat a.txt
E d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep 'e' a.txt
e t k r
[root@linuxprobe test]# grep -i 'e' a.txt
E d 4 9
e t k r

 

加 \< 提取任意字符以特定字符开头的行,例如提取以f开头的行:

[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep '\<f' a.txt
s fafs k m
w fdsfd d g h

 

加 \> 提取任意字符以特定字符结尾的行,例如提取以r结尾的行:

[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep 'r\>' a.txt
2 sfr t s
e trdgt k r

 

-c 用于统计包含特定字符串的所有行数,(不是重复个数),例如出现s的所有行数:

[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep -c 's' a.txt
3

 

-o参数,用于统计出现特定字符串的所有次数,例如出现s的所有次数:

[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep -o 's' a.txt
s
s
s
s
s
[root@linuxprobe test]# grep -o 's' a.txt | wc -l
5

 

-w用于精确匹配,例如提取含有ab的行:

[root@linuxprobe test]# cat a.txt
E d 4 9
s abcde k m
2 ab t s
w abxy d g
e tr k r
[root@linuxprobe test]# grep 'ab' a.txt
s abcde k m
2 ab t s
w abxy d g
[root@linuxprobe test]# grep -w 'ab' a.txt
2 ab t s

 

-E参数,用于同时提取包含一个字符串以上的行,例如同时提取包含k和包含t的行:

[root@linuxprobe test]# cat a.txt
y d 4 9
s e k m
2 b t s
w a d g
e t k r
[root@linuxprobe test]# grep -E 'k|t' a.txt
s e k m
2 b t s
e t k r

  

 

posted @ 2018-07-31 11:10  小鲨鱼2018  阅读(2887)  评论(0编辑  收藏  举报