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

示例

weimz@mzstudio:~$ grep "root" /etc/passwd  # 打印出 /etc/passwd 文件 含有 "root"的行
root:x:0:0:root:/root:/bin/bash
nm-openvpn:x:984:984:NetworkManager OpenVPN:/var/lib/openvpn/chroot:/usr/sbin/nologin
weimz@mzstudio:~$ grep -n "root" /etc/passwd    # 打印出 /etc/passwd 文件 含有 "root"的行在行首现实行号。
1:root:x:0:0:root:/root:/bin/bash
31:nm-openvpn:x:984:984:NetworkManager OpenVPN:/var/lib/openvpn/chroot:/usr/sbin/nologin
weimz@mzstudio:~$ grep -n "root" /etc/passwd    # 打印出 /etc/passwd 文件 含有 "root"的行在行首现实行号。
1:root:x:0:0:root:/root:/bin/bash
31:nm-openvpn:x:984:984:NetworkManager OpenVPN:/var/lib/openvpn/chroot:/usr/sbin/nologin
...

上述程序中 grep: /etc/ModemManager: Is a directory 是非正常的错误输出(也叫标准错误输出),这些错误输出没有使用价值。我们可以在末尾加 2> /dev/null 将标准错误重定向到 /dev/null 这个 黑洞 文件将其丢掉。这样就丢掉了错误信息。如:

weimz@mzstudio:~$ grep "root" /etc/* 2> /dev/null  # 错误重定向后打印查找内容
/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
/etc/bash.bashrc:    debian_chroot=$(< /etc/debian_chroot)
/etc/bash.bashrc:  PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
/etc/brltty.conf:# user (e.g. by root on a Linux/Unix system). The configured defaults are:
...

我个人常用的是 -nr 选项,如:

我要查找我用户主文件夹下 所有包含 "hello world" 的文件内容,如下:

weimz@mzstudio:~$ grep "hello world" -nr  ~/*
/home/weimz/桌面/d.py:1:print("hello world!")
/home/weimz/桌面/b.py:1:print("hello world!")
/home/weimz/桌面/hello.py:1:print("hello world!")
/home/weimz/b.py:1:print("hello world!")
/home/weimz/hello.py:1:print("hello world!")

这样我就可以找到 "hello world" 位于 这些文件的第一行。

练习:

  1. 查找 /etc 文件夹下的哪些文件中含有 root 这个关键字(只查看一级,不查看其中的子文件夹)。
  2. 查找 /usr/include 文件夹下的哪些文件中含有 inet_ntop 这个关键字(搜索所有文件)。