Linux 系统上的grep 是运维中最常用的命令之一。功能特别的丰富。今天咱们就一起看看。
grep
首先创建一个名为test.txt的文件,用于演示使用。
1.grep
可用于在文件中搜索字符串。我们搜索Centos
试试:
$ grep Centos test.txt
Centos
2.与 Linux 中的其他所有内容一样,grep
它也区分大小写。要忽略大小写,我们需要使用-i
参数:
$ grep -i Centos test.txt
Centos
centos
CentOs
3.-n
参数会显示找到每个匹配项的行号。
$ grep -i Centos test.txt
2.Centos
3.centos
7.CentOs
4.我们还可以使用-v 参数
来显示与我们输入关键字相反的结果
$ grep -iv Centos test.txt
Arch Linux
AlmaLinux
Fedora
Red Hat Enterprise Linux
Linux Mint
Debian
Manjaro
openSUSE
8.使用-c
参数,grep 可以计算文件中字符串出现的次数。所以这里 grep 将打印不包含Centos的行在文件中的次数:
$ grep -ivc Centos test.txt
8
9.-x
参数 精确匹配。
$ grep -ix Centos test.txt
Centos
10.系统管理员在搜索日志文件时经常会用到这个场景,显示查找内容的前几行和后几行。-B3
(在匹配前显示 3 行)和-A3
(在匹配后显示 3 行)。
$ grep -B3 -A3 command /var/log/dmesg
[201120] kernel: pcpu-alloc: [0] 0
[201186] kernel: Built 1 zonelists, mobility grouping on. Total pages: 515961
[201188] kernel: Policy zone: DMA32
`[201191] kernel: Kernel command line: BOOT_IMAGE=/boot/vmlinuz-0-59-generic root=UUID=a80ad9d4-90ff-4903-b34d-ca70d82762ed ro quiet splash`
[201563] kernel: Dentry cache hash table entries: 262144 (order: 9, 2097152 bytes, linear)
[201648] kernel: Inode-cache hash table entries: 131072 (order: 8, 1048576 bytes, linear)
[201798] kernel: mem auto-init: stack:off, heap alloc:on, heap free:off
grep 和正则表达式
grep 和正则表达式组合使用,功能更加强大。
1.grep
只返回包含数字的行,我们将使用以下命令:
$ grep [0-9] file.txt
2.grep
返回所有空行:
$ grep -ch ^$ file.txt
3.让我们看看哪一行以L
开头并以数字结尾。^
用于匹配行首,$
用于匹配行尾:
$ grep ^L.*[0-9]$ file.txt
4.要grep
只匹配单词中b
是第三个字符的行,我们可以使用以下命令:
$ grep ..b file.txt`