5.2 grep 命令
grep 这个命令是英文 Global Regular Expression Print 的缩写。 用于在文件内容中搜索匹配的文本模式(字符串或正则表达式),并输出包含匹配模式的行。
命令格式:
grep [选项] "搜索模式" 文件名
常用选项
选项
说明
示例
-n显示匹配行的行号
grep -n "root" /etc/passwd-r / -R递归搜索文件夹下的所有文件
grep -r "hello" ~/-i忽略大小写
grep -i "hello" ~/hello.py-l只输出包含匹配模式的文件名(不显示具体行)
grep -l "main" *.c-c统计匹配到的行数(不是次数)
grep -c "warning" /var/log.txt-w匹配完整单词(避免部分匹配)
grep -w "world" ~/hello.py示例
weimingze@mzstudio:~$ grep "root" /etc/passwd # 打印出 /etc/passwd 文件 含有 "root"的行
root:x:0:0:root:/root:/bin/bash
nm-openvpn:x:121:122:NetworkManager OpenVPN,,,:/var/lib/openvpn/chroot:/usr/sbin/nologin
weimingze@mzstudio:~$ grep -n "root" /etc/passwd # 打印出 /etc/passwd 文件 含有 "root"的行在行首现实行号。
1:root:x:0:0:root:/root:/bin/bash
48:nm-openvpn:x:121:122:NetworkManager OpenVPN,,,:/var/lib/openvpn/chroot:/usr/sbin/nologin
weimingze@mzstudio:~$ grep "root" /etc/* # 打印出 /etc下所有文件包含 "root" 的所有行.
grep: /etc/ModemManager: Is a directory
grep: /etc/NetworkManager: Is a directory
grep: /etc/PackageKit: Is a directory
grep: /etc/UPower: Is a directory
grep: /etc/X11: Is a directory
/etc/aliases:postmaster: root
...
上述程序中 grep: /etc/ModemManager: Is a directory 是非正常的错误输出(也叫标准错误输出),这些错误输出没有使用价值。我们可以在末尾加 2> /dev/null 将标准错误重定向到 /dev/null 这个 黑洞 文件将其丢掉。这样就丢掉了错误信息。如:
weimingze@mzstudio:~$ grep "root" /etc/* 2> /dev/null # 错误重定向后打印查找内容
/etc/aliases:postmaster: root
/etc/anacrontab:HOME=/root
/etc/anacrontab:LOGNAME=root
/etc/bash.bashrc:# set variable identifying the chroot you work in (used in the prompt below)
/etc/bash.bashrc:if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
...
我个人常用的是 -nr 选项,如:
我要查找我用户主文件夹下 所有包含 "hello world" 的文件内容,如下:
weimingze@mzstudio:~$ grep "hello world" -nr ~/*
/home/weimingze/hello.py:1:print("hello world!")
这样我就可以找到 要查找的内容 在位于 /home/weimingze/hello.py 这个文件的第一行。
练习:
- 查找
/etc文件夹下的哪些文件中含有root这个关键字(只查看一级,不查看其中的子文件夹)。 - 查找
/usr/include文件夹下的哪些文件中含有inet_ntop这个关键字(搜索所有文件)。