24.grep 使用手册

文章目录

  • [grep 使用手册](#grep 使用手册)
    • [grep 命令语法](#grep 命令语法)
    • [grep 命令选项](#grep 命令选项)
      • 模式选择和解释选项
        • [-E 选项](#-E 选项)
        • [-e 选项](#-e 选项)
        • [-f 选项](#-f 选项)
        • [-i 选项](#-i 选项)
        • [-w 选项](#-w 选项)
        • [-x 选项](#-x 选项)
      • 输出控制选项
        • [-v 选项](#-v 选项)
        • [-m 选项](#-m 选项)
        • [-c 选项](#-c 选项)
        • [-b 选项](#-b 选项)
        • [-n 选项](#-n 选项)
        • [-o 选项](#-o 选项)
        • [-q 选项](#-q 选项)
        • [-s 选项](#-s 选项)
      • 查找文件选项
        • [-r -R 选项](#-r -R 选项)
        • [-h 和 -H 选项](#-h 和 -H 选项)
        • [-l 和 -L 选项](#-l 和 -L 选项)
      • 输出内容控制选项
        • [-B 选项](#-B 选项)
        • [-A 选项](#-A 选项)
        • [-C 选项](#-C 选项)

grep 使用手册

grep 是 Linux 系统中最重要的命令之一,其功能是从文本文件或管道数据流中筛选匹配的行及数据。

Linux操作文本的三大利器,简称三剑客,分别是:

  • grep:擅长过滤。
  • sed:擅长修改文本。
  • awk:擅长格式化输出。

grep 命令语法

  1. 过滤管道:command | grep [OPTION]... PATTERNS
  2. 过滤文件:grep [OPTION]... PATTERNS [FILE]...

grep 命令帮助信息如下:

bash 复制代码
[root@server ~ 09:23:17]# grep --help
用法: grep [选项]... PATTERN [FILE]...
在每个 FILE 或是标准输入中查找 PATTERN。
默认的 PATTERN 是一个基本正则表达式(缩写为 BRE)。
例如: grep -i 'hello world' menu.h main.c

正则表达式选择与解释:
  -E, --extended-regexp     PATTERN 是一个可扩展的正则表达式(缩写为 ERE)
  -F, --fixed-strings       PATTERN 是一组由断行符分隔的定长字符串。
  -G, --basic-regexp        PATTERN 是一个基本正则表达式(缩写为 BRE)
  -P, --perl-regexp         PATTERN 是一个 Perl 正则表达式
  -e, --regexp=PATTERN      用 PATTERN 来进行匹配操作
  -f, --file=FILE           从 FILE 中取得 PATTERN
  -i, --ignore-case         忽略大小写
  -w, --word-regexp         强制 PATTERN 仅完全匹配字词
  -x, --line-regexp         强制 PATTERN 仅完全匹配一行
  -z, --null-data           一个 0 字节的数据行,但不是空行

Miscellaneous:
  -s, --no-messages         suppress error messages
  -v, --invert-match        select non-matching lines
  -V, --version             display version information and exit
      --help                display this help text and exit

输出控制:
  -m, --max-count=NUM       NUM 次匹配后停止
  -b, --byte-offset         输出的同时打印字节偏移
  -n, --line-number         输出的同时打印行号
      --line-buffered       每行输出清空
  -H, --with-filename       为每一匹配项打印文件名
  -h, --no-filename         输出时不显示文件名前缀
      --label=LABEL         将LABEL 作为标准输入文件名前缀
  -o, --only-matching       show only the part of a line matching PATTERN
  -q, --quiet, --silent     suppress all normal output
      --binary-files=TYPE   assume that binary files are TYPE;
                            TYPE is 'binary', 'text', or 'without-match'
  -a, --text                equivalent to --binary-files=text
  -I                        equivalent to --binary-files=without-match
  -d, --directories=ACTION  how to handle directories;
                            ACTION is 'read', 'recurse', or 'skip'
  -D, --devices=ACTION      how to handle devices, FIFOs and sockets;
                            ACTION is 'read' or 'skip'
  -r, --recursive           like --directories=recurse
  -R, --dereference-recursive
                            likewise, but follow all symlinks
      --include=FILE_PATTERN
                            search only files that match FILE_PATTERN
      --exclude=FILE_PATTERN
                            skip files and directories matching FILE_PATTERN
      --exclude-from=FILE   skip files matching any file pattern from FILE
      --exclude-dir=PATTERN directories that match PATTERN will be skipped.
  -L, --files-without-match print only names of FILEs containing no match
  -l, --files-with-matches  print only names of FILEs containing matches
  -c, --count               print only a count of matching lines per FILE
  -T, --initial-tab         make tabs line up (if needed)
  -Z, --null                print 0 byte after FILE name

文件控制:
  -B, --before-context=NUM  打印以文本起始的NUM 行
  -A, --after-context=NUM   打印以文本结尾的NUM 行
  -C, --context=NUM         打印输出文本NUM 行
  -NUM                      same as --context=NUM
      --group-separator=SEP use SEP as a group separator
      --no-group-separator  use empty string as a group separator
      --color[=WHEN],
      --colour[=WHEN]       use markers to highlight the matching strings;
                            WHEN is 'always', 'never', or 'auto'
  -U, --binary              do not strip CR characters at EOL (MSDOS/Windows)
  -u, --unix-byte-offsets   report offsets as if CRs were not there
                            (MSDOS/Windows)

'egrep'即'grep -E'。'fgrep'即'grep -F'。
直接使用'egrep'或是'fgrep'均已不可行了。
若FILE 为 -,将读取标准输入。不带FILE,读取当前目录,除非命令行中指定了-r 选项。
如果少于两个FILE 参数,就要默认使用-h 参数。
如果有任意行被匹配,那退出状态为 0,否则为 1;
如果有错误产生,且未指定 -q 参数,那退出状态为 2。

请将错误报告给: bug-grep@gnu.org
GNU Grep 主页: <http://www.gnu.org/software/grep/>
GNU 软件的通用帮助: <http://www.gnu.org/gethelp/>

grep 命令选项

模式选择和解释选项

-E 选项

支持扩展正则表达式,相当于 egrep 命令

bash 复制代码
[root@server ~ 09:32:18]# cat words | grep -E '(dog){3}'
dogdogdog

[root@server ~ 09:33:53]# cat words | egrep '(dog){3}'
dogdogdog
-e 选项

使用多个 -e 选项匹配多个PATTERNS

相当于或|

bash 复制代码
[root@server ~ 09:34:15]# cat words | grep -e 'cat' -e 'dog' 
cat
category
acat
concatenate
dog
hello cat kitty
dogdog
dogdogdog
dogg

[root@server ~ 09:36:04]# cat words | egrep 'cat|dog' 
cat
category
acat
concatenate
dog
hello cat kitty
dogdog
dogdogdog
dogg
-f 选项

从文件读取多个 PATTERNS

bash 复制代码
[root@server ~ 09:46:32]# cat words | grep -f file_1 
cat
category
acat
concatenate
dog
hello cat kitty
dogdog
dogdogdog
dogg
-i 选项

忽略大小写匹配

bash 复制代码
[root@server ~ 09:47:35]# grep -i 'cBt' words 
cbt
-w 选项

匹配整个单词都是选项的

bash 复制代码
[root@server ~ 09:48:09]# grep -w 'cat' words 
cat
hello cat kitty
#或者
[root@server ~ 09:49:39]# grep '\bcat\b' words 
cat
hello cat kitty
-x 选项

匹配整行都是选项的

bash 复制代码
[root@server ~ 09:49:55]# cat words | grep -x 'cat'
cat
[root@server ~ 09:52:16]# cat words | grep  '^cat$'
cat

输出控制选项

-v 选项

反向匹配,显示与PATTERNS不匹配的项目

bash 复制代码
[root@server ~ 09:52:32]# cat words | egrep -v '^d|^c'
acat
hello cat kitty
-m 选项

控制最大匹配数目,匹配特定次数后停止匹配

bash 复制代码
[root@server ~ 09:53:49]# cat words | egrep -m 2 'cat'
cat
category

[root@server ~ 09:54:35]# cat words | egrep -m 3 'dog'
dog
dogdog
dogdogdog
-c 选项

显示匹配到项目的数量

bash 复制代码
[root@server ~ 09:54:57]# cat words | egrep -c 'dog'
4
-b 选项

显示匹配项目的字节偏移量

bash 复制代码
[root@server ~ 09:55:39]# head -n 5 words 
cat
category
acat
concatenate
dog
[root@server ~ 09:56:50]# cat words | grep -b 'cat'
0:cat
4:category
13:acat
18:concatenate
74:hello cat kitty
-n 选项

显示匹配项目的行号

bash 复制代码
[root@server ~ 09:57:05]# cat words | grep -n 'cat'
1:cat
2:category
3:acat
4:concatenate
16:hello cat kitty
-o 选项

只显示匹配到的内容,行中其他内容不显示

bash 复制代码
[root@server ~ 09:59:13]# cat words | grep -n 'cat'
1:cat
2:category
3:acat
4:concatenate
16:hello cat kitty

[root@server ~ 09:58:18]# cat words | grep -o -n 'cat'
1:cat
2:cat
3:cat
4:cat
16:cat
-q 选项

不显示任何正常输出。一般用于脚本判定文件中是否包含特定内容。

通过特殊变量 $? 查看是否匹配到内容

bash 复制代码
[root@server ~ 10:00:36]# cat words | grep  -q 'dog'
[root@server ~ 10:00:42]# echo $?
0
#$? 输出0,代表匹配到了内容

[root@server ~ 10:00:45]# cat words | grep  -q 'hi'
[root@server ~ 10:01:46]# echo $?
1
#$? 输出1,代表没有匹配到内容
-s 选项

不显示任何错误输出

bash 复制代码
[dcr@server ~ 10:03:35]$ grep '^SELINUX=' /etc/shadow /etc/selinux/config
grep: /etc/shadow: 权限不够
/etc/selinux/config:SELINUX=disabled

[dcr@server ~ 10:03:47]$ grep -s '^SELINUX=' /etc/shadow /etc/selinux/config
/etc/selinux/config:SELINUX=disabled

查找文件选项

-r -R 选项
  • -r,递归匹配目录。
  • -R,递归匹配目录,跟随软链接。
bash 复制代码
[root@server ~ 10:20:32]# grep -r 'enforc' /etc/
/etc/services:stss            3090/tcp                # Senforce Session Services
/etc/services:stss            3090/udp                # Senforce Session Services
/etc/selinux/config:#     enforcing - SELinux security policy is enforced.
/etc/selinux/config:#     permissive - SELinux prints warnings instead of enforcing.
/etc/selinux/targeted/active/file_contexts:/usr/lib/systemd/system/ods-enforcerd.service	--	system_u:object_r:opendnssec_unit_file_t:s0
/etc/selinux/targeted/active/file_contexts:/usr/sbin/ods-enforcerd	--	system_u:object_r:opendnssec_exec_t:s0
匹配到二进制文件 /etc/selinux/targeted/active/policy.kern
/etc/selinux/targeted/contexts/files/file_contexts:/usr/lib/systemd/system/ods-enforcerd.service	--	system_u:object_r:opendnssec_unit_file_t:s0
/etc/selinux/targeted/contexts/files/file_contexts:/usr/sbin/ods-enforcerd	-- system_u:object_r:opendnssec_exec_t:s0
匹配到二进制文件 /etc/selinux/targeted/contexts/files/file_contexts.bin
匹配到二进制文件 /etc/selinux/targeted/policy/policy.31
/etc/security/limits.conf:#        - "soft" for enforcing the soft limits
/etc/security/limits.conf:#        - "hard" for enforcing hard limits
/etc/security/namespace.conf:# of 000. pam_namespace module will enforce this mode unless it
-h 和 -H 选项
  • -h,不显示匹配项目所在文件的文件名(只显示内容)。
  • -H,显示匹配项目所在文件的文件名,默认情况使用该选项。
bash 复制代码
#-h
[root@server ~ 10:20:45]# grep -r -h 'enforc' /etc/
stss            3090/tcp                # Senforce Session Services
stss            3090/udp                # Senforce Session Services
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
/usr/lib/systemd/system/ods-enforcerd.service	--	system_u:object_r:opendnssec_unit_file_t:s0
/usr/sbin/ods-enforcerd	--	system_u:object_r:opendnssec_exec_t:s0
匹配到二进制文件 /etc/selinux/targeted/active/policy.kern
/usr/lib/systemd/system/ods-enforcerd.service	--	system_u:object_r:opendnssec_unit_file_t:s0
/usr/sbin/ods-enforcerd	--	system_u:object_r:opendnssec_exec_t:s0
匹配到二进制文件 /etc/selinux/targeted/contexts/files/file_contexts.bin
匹配到二进制文件 /etc/selinux/targeted/policy/policy.31
#        - "soft" for enforcing the soft limits
#        - "hard" for enforcing hard limits
# of 000. pam_namespace module will enforce this mode unless it

#-H(默认就是显示文件和内容)
[root@server ~ 10:22:12]# grep -r -H 'enforc' /etc/
/etc/services:stss            3090/tcp                # Senforce Session Services
/etc/services:stss            3090/udp                # Senforce Session Services
/etc/selinux/config:#     enforcing - SELinux security policy is enforced.
/etc/selinux/config:#     permissive - SELinux prints warnings instead of enforcing.
/etc/selinux/targeted/active/file_contexts:/usr/lib/systemd/system/ods-enforcerd.service	--	system_u:object_r:opendnssec_unit_file_t:s0
/etc/selinux/targeted/active/file_contexts:/usr/sbin/ods-enforcerd	--	system_u:object_r:opendnssec_exec_t:s0
匹配到二进制文件 /etc/selinux/targeted/active/policy.kern
/etc/selinux/targeted/contexts/files/file_contexts:/usr/lib/systemd/system/ods-enforcerd.service	--	system_u:object_r:opendnssec_unit_file_t:s0
/etc/selinux/targeted/contexts/files/file_contexts:/usr/sbin/ods-enforcerd	-- system_u:object_r:opendnssec_exec_t:s0
匹配到二进制文件 /etc/selinux/targeted/contexts/files/file_contexts.bin
匹配到二进制文件 /etc/selinux/targeted/policy/policy.31
/etc/security/limits.conf:#        - "soft" for enforcing the soft limits
/etc/security/limits.conf:#        - "hard" for enforcing hard limits
/etc/security/namespace.conf:# of 000. pam_namespace module will enforce this mode unless it
-l 和 -L 选项
  • -l,对目录匹配时,只显示那些包含匹配模式的文件的名称。
  • -L,对目录匹配时,只显示那些不包含匹配模式的文件的名称。
bash 复制代码
[root@server ~ 10:22:48]# grep -r -l 'enforc' /etc/
/etc/services
/etc/selinux/config
/etc/selinux/targeted/active/file_contexts
/etc/selinux/targeted/active/policy.kern
/etc/selinux/targeted/contexts/files/file_contexts
/etc/selinux/targeted/contexts/files/file_contexts.bin
/etc/selinux/targeted/policy/policy.31
/etc/security/limits.conf
/etc/security/namespace.conf

[root@server ~ 10:25:15]# grep -r -L 'enforc' /etc/
#只显示没有匹配的项目文件名

输出内容控制选项

-B 选项

显示匹配项目本身,以及前多少行

bash 复制代码
[root@server ~ 10:27:41]# ip addr | grep '00:0c:29:53:86:a6'
    link/ether 00:0c:29:53:86:a6 brd ff:ff:ff:ff:ff:ff

#查看显示对应的link的网卡名
[root@server ~ 10:28:08]# ip addr | grep -B 1 '00:0c:29:53:86:a6'
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:53:86:a6 brd ff:ff:ff:ff:ff:ff
-A 选项

显示匹配项目本身,以及后多少行

bash 复制代码
[root@server ~ 10:28:27]# ip addr | grep -A 1 '00:0c:29:53:86:a6'
    link/ether 00:0c:29:53:86:a6 brd ff:ff:ff:ff:ff:ff
    inet 10.1.8.10/24 brd 10.1.8.255 scope global noprefixroute ens33
#后一行显示对应的ip地址
-C 选项

显示匹配项目本身,以及前后多少行

bash 复制代码
[root@server ~ 10:29:29]# ip addr | grep -C 1 '00:0c:29:53:86:a6'
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:53:86:a6 brd ff:ff:ff:ff:ff:ff
    inet 10.1.8.10/24 brd 10.1.8.255 scope global noprefixroute ens33
    
#显示以匹配目标为中心的前后一行
相关推荐
心灵宝贝2 小时前
libopenssl1_0_0-1.0.2p-3.49.1.x86_64安装教程(RPM包手动安装步骤+依赖解决附安装包下载)
linux·运维·服务器
tryCbest2 小时前
Windows和Linux设置Https(SSL)访问
linux·windows·https
btyzadt3 小时前
Ubuntu中安装Nuclei教程
linux·运维·ubuntu
倔强的石头1063 小时前
【Linux指南】gdb进阶技巧:断点高级玩法与变量跟踪实战
linux·运维
山,离天三尺三4 小时前
基于LINUX平台使用C语言实现MQTT协议连接华为云平台(IOT)(网络编程)
linux·c语言·开发语言·网络·物联网·算法·华为云
用户31187945592185 小时前
libopenssl-1_0_0-devel-1.0.2p RPM 包安装教程(openSUSE/SLES x86_64)
linux
waves浪游6 小时前
Linux基本指令(中)
linux·运维·python
zwhy03116 小时前
TCP服务器设计思路
linux·服务器·网络
-水火-7 小时前
【IDE】Linux下使用openocd烧录bin文件
linux·ide·openocd·bin