码迷,mamicode.com
首页 > 系统相关 > 详细

linux grep命令

时间:2020-07-01 16:11:56      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:grub2   cti   说明   list   reg   uniq   参考   ESS   文件内容   

grep [选项] PATTERN [文件]

说明:grep(global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

在每个文件或标准输入中查找PATTERN

默认的PATTERN是一个基本正则表达式(缩写为BRE)

(1).常用选项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-A,--after-context=NUM 输出当前行以及向后数NUM数的所有行
-B,--before-context=NUM 输出当前行以及向前数NUM数的所有行
-C,--context=NUM 输出当前行以及向前向后各数NUM数的所有行
-c,--count 统计每个文件中包含指定字符串的行数
-e,--regexp=PATTERN 用PATTERN来进行匹配操作
-E,--extended-regexp PATTERN是一个可扩展的正则表达式(缩写ERE)
-f<范本文件>,--file=FILE 指定范本文件,其内容有一个或多个范本样式,让grep查找符合范本条件的文件内容,格式为每一行的范本样式
-F,--fixed-strings PATTERN是一个由断行符分隔的定长字符串(取消默认的基本正则表达式)
-h,--no-filename 输出时不显示文件名前缀
-i,--ignore-case 忽略大小写
-l,--files-with-match 只显示包含指定字符串的文件名
-n,--line-number 输出的同时显示行号
-o,--only-matching 只显示匹配到的字符串
-q,--quiet,--silent 静默模式,不输出任何信息
-s,--nomessages 不显示不存在或无法匹配的错误信息
-v,--invert-march 显示不匹配的行
-V,-version 显示版本信息
-w,--word-regexp 匹配整个单词
--color=auto 对匹配到的文本着色显示

(2).了解基本正则表达式和扩展正则表达式

基本正则表达式(BRE

              元字符分类:字符匹配、匹配次数、位置锚定、分组

              i. 字符匹配: 

                   . 匹配任意单个字符                  # 需要匹配“.”字符时,用 \. 或 [.] 表示

                  [] 匹配指定范围内的任意单个字符

                  [^] 匹配指定范围外的任意单个字符

                  [:alnum:] 字母和数字

                  [:alpha:] 代表任何英文大小写字符,亦即 A-Z, a-z

                  [:lower:] 小写字母 [:upper:] 大写字母

                  [:blank:] 空白字符(空格和制表符)

                  [:space:] 水平和垂直的空白字符(比[:blank:]包含的范围广)

                  [:cntrl:] 不可打印的控制字符(退格、删除、警铃...)

                  [:digit:] 十进制数字 [:xdigit:]十六进制数字

                  [:graph:] 可打印的非空白字符

                  [:print:] 可打印字符

                  [:punct:] 标点符号

             ii. 匹配次数:用在要指定次数的字符后面,用于指定前面的字符要出现的次数

                  * 匹配前面的字符任意次,包括0次

                            贪婪模式:尽可能长的匹配

                 .* 任意长度的任意字符

                 \? 匹配其前面的字符0或1次

                 \+ 匹配其前面的字符至少1次 (非贪婪模式,懒惰模式)

                 \{n\} 匹配前面的字符n次

                 \{m,n\} 匹配前面的字符至少m次,至多n次

                 \{,n\} 匹配前面的字符至多n次

                 \{n,\} 匹配前面的字符至少n次

            iii. 位置锚定:定位出现的位置

                 ^ 行首锚定,用于模式的最左侧。例:^#,以#开头

                 $ 行尾锚定,用于模式的最右侧。例:#$,以#结尾

                ^PATTERN$ 用于模式匹配整行

                         ^$ 空行

                         ^[[:space:]]*$ 空白行

                 \< 或 \b 词首锚定,用于单词模式的左侧

                 \> 或 \b 词尾锚定;用于单词模式的右侧

                 \<PATTERN\> 匹配整个单词

            iv. 分组:

     \(\) 将一个或多个字符捆绑在一起,当作一个整体进行处理,如:\(root\)\+

                 分组括号中的模式匹配到的内容会被正则表达式引擎记录于内部的变量中,这些变量的命名方式为: \1, \2, \3, ...

                 \1  表示从左侧起第一个左括号以及与之匹配右括号之间的模式所匹配到的字符

                        示例:  \(string1\+\(string2\)*\)           \1 :string1\+\(string2\)*        \2 :string2

                        注:后向引用:引用前面的分组括号中的模式所匹配字符,而非模式本身

                 或者:\|

                        示例:a\|b: a或b  C\|cat: C或cat   \(C\|c\)at:Cat或cat

扩展正则表达式(ERE

            扩展正则表达式的元字符:字符匹配、匹配次数、位置锚定、分组 (与基本正则表达式基本相同;用法相似,除了词首、词尾锚定一样,其他只是在基本正则表达式中去掉转义字符)

            与基本正则表达式的比较:写法上比较简单,去掉了大量的转义字符;但需要匹配特殊字符时,扩展正则表达式需将特殊字符用 [] 括起来使用,这时用基本正则表达式比较方便

   格式: egrep [OPTIONS] PATTERN [FILE...]

          egrep = grep -E(等价)

           i.   字符匹配 (与基本正则表达式基本相同)

           ii.  位置锚定:

                 ^ :行首

                 $ :行尾

                 \<, \b :语首

                 \>, \b :语尾

          iii.  分组:

              ()

              后向引用:\1, \2, ...

          iv.  或者:

     |

     示例:  a|b: a或b    C|cat: C或cat      (C|c)at:Cat或cat

正则表达式例题:

1、显示/proc/meminfo文件中以大小s开头的行(要求:使用两种方法)

         i.  cat /proc/meminfo |grep -i "^s"

        ii.  cat /proc/meminfo |grep  "^\(s\|S\)"  注意:\(和\|以及\)都是转义字符

2、显示/etc/passwd文件中不以/bin/bash结尾的行

          cat /etc/passwd |grep -v ":/bin/bash$"

3、显示用户rpc默认的shell程序

          cat /etc/passwd |grep -w "^rpc" |cut -d: -f 7

4、找出/etc/passwd中的两位或三位数

          cat /etc/passwd |grep -wo "[[:digit:]]\{2,3\}"

5、显示CentOS7的/etc/grub2.cfg文件中,至少以一个空白字符开头的且后面有非空白字符的行

          cat /etc/grub2.cfg | grep "^[[:space:]]\+[^‘ ‘].*" 或   cat /etc/grub2.cfg | grep "^[[:space:]]\+[^[:space:]].*"

6、找出“netstat -tan”命令结果中以LISTEN后跟任意多个空白字符结尾的行

          netstat -tan | grep ".*LISTEN[[:space:]]*$"

7、显示CentOS7上所有系统用户的用户名和UID

         cat /etc/passwd |cut -d: -f1,3 |grep -w "[1-9][0-9]\{,2\}$"

8、添加用户bash、testbash、basher、sh、nologin(其shell为/sbin/nologin),找出/etc/passwd用户名和shell同名的行

         cat /etc/passwd |grep -w "^\([^:]*\):.*/\1$"

9、利用df和grep,取出磁盘各分区利用率,并从大到小排序

        df |grep "^/dev/sd"|grep -wo "[0-9]\+%"|sort -nr

10、显示三个用户root、mage、wang的UID和默认shell

         cat /etc/passwd |grep -w "^\(root\|mage\|wang\)" |cut -d: -f 3,7

11、找出/etc/rc.d/init.d/functions文件中行首为某单词(包括下划线)后面跟一个小括号的行

         cat /etc/rc.d/init.d/functions |grep -i "^\([_[:alnum:]]\+(\)"

12、使用egrep取出/etc/rc.d/init.d/functions中其基名

           echo "/etc/rc.d/init.d/functions" | grep -Eo "[^/]*[/]?$"|tr -d "/"

13、使用egrep取出上面路径的目录名

          echo "/etc/rc.d/init.d/" | grep -Eo "..*[/]\<"

14、统计last命令中以root登录的每个主机IP地址登录次数

        last |grep -w "^root.*\<pts" |  grep -wE "((([0-9])|([1-9][0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-9])|([1-9][0-9])|(1[0-9]{,2})|(2[0-4][0-9])|(25[0-5])){1}[[:space:]]" |tr -s " "|cut -d " " -f3|sort|uniq -c  

15、利用扩展正则表达式分别表示0-9、10-99、100-199、200-249、250-255

           [0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]

16、显示ifconfig命令结果中所有IPv4地址

          ifconfig |grep -owE "((([0-9]{1,2})|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-9]{1,2})|(1[0-9]{,2})|(2[0-4][0-9])|(25[0-5])){1}[[:space:]]"

17、将此字符串:welcome to  magedu linux 中的每个字符去重并排序,重复次数多的排到前面

              cat test | grep -o "[[:lower:]]"|sort |uniq -c|sort -nr |tr -s ‘ ‘ | cut -d " " -f 3 |tr -d ‘\n‘

注:匹配有效ip地址:

          i. grep -owE "((([0-9])|([1-9][0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-9])|([1-9][0-9])|(1[0-9]{,2})|(2[0-4][0-9])|(25[0-5])){1}[[:space:]]"                    -E : 代表扩展正则表达式

         ii.  grep -owE "((([0-9]{1,2})|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-9]{1,2})|(1[0-9]{,2})|(2[0-4][0-9])|(25[0-5])){1}[[:space:]]" 

(3).实例

在特定的文本集中查找特定字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@CentOS6 桌面]# cat >t1.txt<<EOF
> I‘m MenAngel!
> Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
> EOF
[root@CentOS6 桌面]# cat >t2.txt<<EOF
> Every one fights for a better future,but I fight for freedom!
> EOF
[root@CentOS6 桌面]# cat >t3.txt<<EOF
> There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
> When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.
> EOF
[root@CentOS6 桌面]# grep "MenAngel" t1.txt t2.txt t3.txt
t1.txt:I‘m MenAngel!

 输出指定字符串所在行之外的所有文件的行内容

1
2
3
4
5
[root@CentOS6 桌面]# grep -v "MenAngel" t1.txt t2.txt t3.txt
t1.txt:Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
t2.txt:Every one fights for a better future,but I fight for freedom!
t3.txt:There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
t3.txt:When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.

将查找的字符串用特定的颜色标记出来

1
2
[root@CentOS6 桌面]# grep "fight" t1.txt t2.txt t3.txt --color=auto
t2.txt:Every one fights for a better future,but I fight for freedom!

统计每个文件中包含指定字符串的行数

1
2
3
4
5
是行数,不是总数,一行有两个指定字符串也只算一次
[root@CentOS6 桌面]# grep -c "that" t1.txt t2.txt t3.txt
t1.txt:1
t2.txt:0
t3.txt:2

默认情况,输出包含特定字符串所在的行

1
2
3
4
5
6
7
8
[root@CentOS6 桌面]# grep -n "that" t1.txt t2.txt t3.txt
t1.txt:2:Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
t3.txt:1:There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
t3.txt:2:When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.
[root@CentOS6 桌面]# grep "that" t1.txt t2.txt t3.txt
t1.txt:Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
t3.txt:There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
t3.txt:When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.

配合cat查找文件中指定字符串所在的行

1
2
3
4
[root@CentOS6 桌面]# cat t1.txt t2.txt t3.txt | grep "MenAngel"
I‘m MenAngel!
[root@CentOS6 桌面]# grep "MenAngel" t1.txt t2.txt t3.txt
t1.txt:I‘m MenAngel!

查找以指定字符串开头的文本行并输出

1
2
3
4
[root@CentOS6 桌面]# cat t1.txt t2.txt t3.txt | grep ^I
I‘m MenAngel!
[root@CentOS6 桌面]# cat t1.txt t2.txt t3.txt | grep ^M   //没有以M开头的行
[root@CentOS6 桌面]#

输出不以指定字符串开头的文本所在行的内容

1
2
3
4
5
[root@CentOS6 桌面]# cat t1.txt t2.txt t3.txt | grep ^[^I]
Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
Every one fights for a better future,but I fight for freedom!
There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.

显示特定行前后内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@CentOS6 桌面]# seq 10 | grep "5" -C 3
2
3
4
5
6
7
8
[root@CentOS6 桌面]# seq 10 | grep "5" -A 3
5
6
7
8
[root@CentOS6 桌面]# seq 10 | grep "5" -B 3
2
3
4
5

不管特定行前后行数是否足够,参数都是可用的

1
2
3
[root@CentOS6 桌面]# grep -C 3 "MenAngel" t1.txt t2.txt t3.txt
t1.txt:I‘m MenAngel!
t1.txt-Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!

如果匹配特定行前后内容有多个结果,会有--分割,但不会重复显示

1
2
3
4
5
6
7
8
9
10
11
[root@CentOS6 桌面]# grep -A 1 "that" t1.txt t2.txt t3.txt
t1.txt:Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
--
t3.txt:There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
t3.txt:When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.
[root@CentOS6 桌面]# grep -B 1 "that" t1.txt t2.txt t3.txt
t1.txt-I‘m MenAngel!
t1.txt:Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
--
t3.txt:There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
t3.txt:When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.

匹配多个字符串

1
2
3
4
5
6
[root@CentOS6 桌面]# grep -e "MenAngel" -e "that" -o t1.txt t2.txt t3.txt
t1.txt:MenAngel
t1.txt:that
t3.txt:that
t3.txt:that
t3.txt:that

匹配样本文件中每行字符串

1
2
3
4
5
6
7
8
9
[root@CentOS6 桌面]# cat >patfile<<EOF
> MenAngel
> that
> EOF
[root@CentOS6 桌面]# grep -f patfile t1.txt t2.txt t3.txt
t1.txt:I‘m MenAngel!
t1.txt:Although I‘m still a poor student right now,I believe that someday I will be one of the successful man in the world!
t3.txt:There is no one hoping that you will succeed when you are been looking down upon,but if you succeeded,they will look down upon themselves!
t3.txt:When you get an important thing,you will find that it is not so precious as you like,but when you lose it after that,it will become so precious as you liked.

参考资料:

https://www.cnblogs.com/Dlg-Blog/p/8733908.html

http://www.cnblogs.com/MenAngel/p/5547219.html

linux grep命令

标签:grub2   cti   说明   list   reg   uniq   参考   ESS   文件内容   

原文地址:https://www.cnblogs.com/heboxiang/p/13219485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!