本文提供了关于Linux文件系统中如何查找特定目录或包含特定单词或字符串的所有文件的有用技巧。
约定# - 要求直接以root用户身份或使用sudo命令以root权限执行给定的命令
$ - 给定的命令作为一个普通的非特权用户执行
示例 以非递归方式查找具有特定字符串的所有文件第一个命令示例将在/etc/目录下的所有文件中搜索字符串artful,同时排除任何子目录:
linuxidc@linuxidc:~$ grep -s artful /etc/*
/etc/lsb-release:DISTRIB_CODENAME=artful
/etc/os-release:VERSION_CODENAME=artful
/etc/os-release:Ubuntu_CODENAME=artful
grep -s 选项将禁止关于不存在或不可读文件的错误消息。 输出显示文件名以及打印包含请求字符串的实际行。
如下图:
递归地查找具有特定字符串的所有文件以上命令省略了所有的子目录。 递归搜索意味着遍历所有的子目录。 以下命令将在/etc/目录内的所有文件(包括所有子目录)中搜索字符串artful:
linuxidc@linuxidc:~$ sudo grep -R artful /etc/*
[sudo] linuxidc 的密码:
/etc/apt/sources.list.save:# deb cdrom:[Ubuntu 17.10 _Artful Aardvark_ - Release amd64 (20171018)]/ artful main restricted
/etc/apt/sources.list.save:deb artful main restricted
/etc/apt/sources.list.save:# deb-src artful main restricted
/etc/apt/sources.list.save:deb artful-updates main restricted
/etc/apt/sources.list.save:# deb-src artful-updates main restricted
/etc/apt/sources.list.save:deb artful universe
/etc/apt/sources.list.save:# deb-src artful universe
/etc/apt/sources.list.save:deb artful-updates universe
......
/etc/dictionaries-common/words:artful
/etc/dictionaries-common/words:artfully
/etc/dictionaries-common/words:artfulness
/etc/dictionaries-common/words:artfulness's
/etc/lsb-release:DISTRIB_CODENAME=artful
/etc/os-release:VERSION_CODENAME=artful
/etc/os-release:UBUNTU_CODENAME=artful
如下图
搜索包含特定单词的所有文件上面的grep命令示例列出了包含字符串artful的所有文件。 也显示了artfules,artfuled等。 使用grep -w选项只显示一个特定的单词:
linuxidc@linuxidc:~$ sudo grep -Rw artful /etc/*
[sudo] linuxidc 的密码:
/etc/apt/sources.list.save:# deb cdrom:[Ubuntu 17.10 _Artful Aardvark_ - Release amd64 (20171018)]/ artful main restricted
/etc/apt/sources.list.save:deb artful main restricted
/etc/apt/sources.list.save:# deb-src artful main restricted
/etc/apt/sources.list.save:deb artful-updates main restricted
/etc/apt/sources.list.save:# deb-src artful-updates main restricted
/etc/apt/sources.list.save:deb artful universe
......
/etc/dictionaries-common/words:artful
/etc/lsb-release:DISTRIB_CODENAME=artful
/etc/os-release:VERSION_CODENAME=artful
/etc/os-release:UBUNTU_CODENAME=artful
如下图:
仅列出包含特定文字的文件名称
上述命令可能会产生不必要的输出。 下一个示例将只递归地显示包含/etc/目录下的字符串artful的所有文件名:
linuxidc@linuxidc:~$ sudo grep -Rl artful /etc/*
/etc/apt/sources.list.save
/etc/apt/sources.list
/etc/apt/sources.list.d/noobslab-ubuntu-deepin-sc-artful.list
/etc/apt/sources.list.d/openshot_developers-ubuntu-ppa-artful.list
/etc/apt/sources.list.d/forkotov02-ubuntu-ppa-artful.list
/etc/apt/sources.list.d/forkotov02-ubuntu-ppa-artful.list.save
/etc/apt/sources.list.d/openshot_developers-ubuntu-ppa-artful.list.save
/etc/dictionaries-common/words
/etc/lsb-release
/etc/os-release
如下图: