rgrep.
rgrep
是grep
的递归版本。
rgrep
类似于grep -R
。
- 递归所有文件,搜索字符串“Linux”。
$rgrep -i linux * dir1/RHEL-based.txt:AlmaLinux dir1/RHEL-based.txt:Red Hat Enterprise Linux dir2/Debian-based.txt:Linux Mint
grep 和 regex
grep和正则表达式可以一起使用。
- 搜索仅包含数字的行:
$grep [0-9] file.txt
- 统计文件中的所有空行:
$grep -ch ^$file.txt
- 查找以“l”开头,并以数字结尾的行。
^
用于匹配行的开头,并且使用$
匹配行的结尾:
$grep ^L.*[0-9]$file.txt
- 查找单词中的第三个字符是b的行:
$grep ..b file.txt
egrep.
eGrep
是grep
的扩展版本。
换句话说,eGrep
等于grep -e
。
EGREP支持更多正则表达式模式。
- 搜索两个p字符的行:
$egrep p{2} file.txt OR $grep pp file.txt OR $grep -E p{2} file.txt
- 查找以“S”或者“A”结尾的行:
$egrep "S$|A$" file.txt
fgrep
FGREP
是“grep”的快速版本,不支持正则表达式,因此被认为是更快的。fgrep
等同于grep -f
。
- 简单搜索
$fgrep Fedora distros.txt Fedora
- fgrep不能使用正则表达式,所以输出为空
$fgrep -i linux$distros.txt $grep -i linux$distros.txt Arch Linux AlmaLinux Red Hat Enterprise Linux
grep
为了演示,我们创建了一个名为“distrs.txt”的简单文本文件,其中包含了linux发行版本的名称。
grep
可用于搜索文件中的字符串。
$grep Ubuntu distros.txt Ubuntu
grep
也区分大小写。要忽略大小写,我们需要使用-i
选项:
$grep -i ubuntu distros.txt Ubuntu Kubuntu Xubuntu
- “-n”选项将显示每个匹配项所在的行号。
$grep -i -n ubuntu distros.txt 3:Ubuntu 8:Kubuntu 9:Xubuntu
- 我们还可以使用“-v”(反转)选项来显示与搜索模式不匹配的行。
$grep -iv ubuntu distros.txt Arch Linux AlmaLinux Fedora Red Hat Enterprise Linux CentOS Linux Mint Debian Manjaro openSUSE
- 使用“-c”选项,grep可以计算文件中字符串出现的次数。因此,下面的grep将打印Ubuntu未出现在文件中的次数:
$grep -ivc ubuntu distros.txt 9
- “-x”选项将仅打印精确的引用。
$grep -ix ubuntu distros.txt Ubuntu
- 在搜索日志文件时,系统管理员肯定很喜欢下面这个示例
-B3
(匹配前显示3行)和-A3
(匹配后显示3行)为输出提供更多上下文。
$grep -B3 -A3 command /var/log/dmesg [ 0.201120] kernel: pcpu-alloc: [0] 0 [ 0.201186] kernel: Built 1 zonelists, mobility grouping on. Total pages: 515961 [ 0.201188] kernel: Policy zone: DMA32 [ 0.201191] kernel: Kernel command line: BOOT_IMAGE=/boot/vmlinuz-5.8.0-59-generic root=UUID=a80ad9d4-90ff-4903-b34d-ca70d82762ed ro quiet splash [ 0.201463] kernel: Dentry cache hash table entries: 262144 (order: 9, 2097152 bytes, linear) [ 0.201448] kernel: Inode-cache hash table entries: 131072 (order: 8, 1048576 bytes, linear) [ 0.201598] kernel: mem auto-init: stack:off, heap alloc:on, heap free:off
日期:2020-07-07 20:56:44 来源:oir作者:oir