那些城市那些花

导航

grep 命令详解

grep简介
grep [-acinv] [--color=auto] '匹配的字串' 文件名称
选项与参数:
-a :将二进制文件以text文件的方式匹配
-c :统计匹配到的字串次数
-i :忽略大小写
-n :输出行号
-v :反向选择,不输出匹配项
-E : 使用正则匹配
-o : 单独取出匹配项
-A : 下文匹配
-B : 下文匹配
--color=auto :将匹配项高亮颜色输出

grep -c 使用 统计root共2次

[root@shell-test ~]# grep -c root /etc/passwd
2

grep -i 使用 Started没有区分大小写

[root@shell-test log]# grep -i ****started**** messages|tail
Aug 10 04:20:01 shell-test systemd: ****Started**** Session 45 of user root.
Aug 10 04:20:01 shell-test systemd: Started Session 46 of user root.

grep -n 使用 开头为行号

grep -n Started messages|tail
105:Aug 10 04:20:01 shell-test systemd: ****Started**** Session 45 of user root.
107:Aug 10 04:20:01 shell-test systemd: ****Started**** Session 46 of user root.

grep -v 使用 反向匹配Started

grep -v Started messages|tail
Aug 10 04:20:27 shell-test systemd: Starting Session 48 of user root.
Aug 10 04:20:27 shell-test systemd-logind: New session 49 of user root

grep -E 使用 匹配两个字串

[root@shell-test log]# grep -E 'Started|Starting' messages|tail
Aug 10 04:30:01 shell-test systemd: ****Started**** Session 52 of user root.
Aug 10 04:30:01 shell-test systemd: ****Starting**** Session 52 of user root.

grep -o 使用 只取出匹配字串

[root@shell-test log]# grep -o Started messages|tail
Started
Started

grep -i root -A 3 使用 显示root下三行

grep -i root -A 3 /etc/passwd
root::0:0:root:/****root****:/bin/bash
bin::1:1:bin:/bin:/sbin/nologin
daemon::2:2:daemon:/sbin:/sbin/nologin

grep -i root -B 3 使用 显示root上三行 --color为匹配字串加颜色

grep -i root -B 3 /etc/passwd --color 
halt::7:0:halt:/sbin:/sbin/halt
mail::8:12:mail:/var/spool/mail:/sbin/nologin
operator::11:0:operator:/****root****:/sbin/nologin

grep -r '匹配字串' * #在当前目录及其子目录下搜索匹配字串行的文件
grep -l -r '匹配字串' * #在当前目录及其子目录下搜索匹配子串行的文件,但是不显示匹配的行,只显示匹配的文件

grep 正则表达式

grep -n 'r[ao]t' 匹配rot或rat的项

grep -n 'r[oa]t' /etc/passwd
10:operator:x:11:0:operator:/root:/sbin/nologin
17:sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin

grep -n '[^r]oo' 匹配不是r开头后面跟oo的项

[root@shell-test log]# grep -n '[^r]oo' /etc/passwd
5:lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
9:mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
18:postfix:x:89:89::/var/spool/postfix:/sbin/nologin
22:loop:x:1001:1001::/home/loop:/bin/bash

grep -n '^[r]oo' 匹配r开头后面跟oo的项

[root@shell-test log]# grep -n '^[r]oo' /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
egrep  '^[0-9]' 匹配0-9开头的项这个是个例子实际需要灵活应用
egrep  '^\.' \是转义符把.转换为普通的点匹配以.开头的隐藏文件
egrep  '^$' 匹配出空白行
egrep  .. 是匹配两个字符
egrep  * 是匹配任意字符
egrep  a+ 出现一次或多次
egrep a.? a后面跟0个或1个项
egrep -n 'o\{2\}' 匹配出现两次o的项
egrep -n 'o\{3,5\}' 匹配出现3-5次o的项

posted on 2023-01-29 10:15  那些城市那些花  阅读(393)  评论(0编辑  收藏  举报