如何在 Linux 的文件和目录中查找特定字符串或单词

linuxoperating systemfile system更新于 2026/2/16 4:52:17

很多时候,我们需要搜索可能存在于多个文件中的特定字符串。在本文中,我们将了解使用哪些命令来查找包含特定字符串或单词的所有文件。

使用 grep

它是一个强大的正则表达式搜索工具。在基本层面上,它会将输入字符串与包含该字符串的文件列表进行匹配。以下是语法和示例。

grep 'string' directory-path/*.*
#Example
grep 'config' hadoop-2.6.5/etc/hadoop/*.*

运行上述代码得到以下结果 −

hadoop-2.6.5/etc/hadoop/capacity-scheduler.xml: <configuration>
hadoop-2.6.5/etc/hadoop/core-site.xml:<configuration>
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml:<configuration>
hadoop-2.6.5/etc/hadoop/hdfs-site.xml:<configuration>
hadoop-2.6.5/etc/hadoop/httpfs-site.xml:<configuration>
hadoop-2.6.5/etc/hadoop/kms-acls.xml:<configuration>
hadoop-2.6.5/etc/hadoop/kms-site.xml:<configuration>
hadoop-2.6.5/etc/hadoop/mapred-site.xml.template:<configuration>
hadoop-2.6.5/etc/hadoop/ssl-client.xml.example:<configuration>
hadoop-2.6.5/etc/hadoop/ssl-server.xml.example:<configuration>
hadoop-2.6.5/etc/hadoop/yarn-site.xml:<configuration>

使用 grep -r

在本例中,我们提到了 r 开关,它允许沿给定路径的所有子目录进行递归搜索。

grep -r 'string' directory-path/
$ grep -r 'done' hadoop-2.6.5/

运行上述代码得到以下结果 −

hadoop-2.6.5/sbin/slaves.sh:done
hadoop-2.6.5/sbin/distribute-exclude.sh:done
hadoop-2.6.5/sbin/yarn-daemon.sh:done
hadoop-2.6.5/sbin/kms.sh:done
hadoop-2.6.5/sbin/httpfs.sh:done
hadoop-2.6.5/sbin/refresh-namenodes.sh: done
hadoop-2.6.5/sbin/refresh-namenodes.sh: echo "Refresh of namenodes done."
hadoop-2.6.5/sbin/mr-jobhistory-daemon.sh: done
hadoop-2.6.5/sbin/hadoop-daemon.sh:done

使用 egrep –r 'word1|word2'

我们还可以使用带有 | 字符的 egrep 命令来搜索多个单词。在下面的示例中,我们搜索包含单词 config 或单词 comma 的文件。

egrep -r 'word1|word2' directory-path/
#Example
egrep -r 'config|comma' hadoop-2.6

运行上述代码得到以下结果 −

hadoop-2.6.5/etc/hadoop/capacity-scheduler.xml:<configuration>
hadoop-2.6.5/etc/hadoop/capacity-scheduler.xml:</configuration>
hadoop-2.6.5/etc/hadoop/core-site.xml:&tl;?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
hadoop-2.6.5/etc/hadoop/core-site.xml:<configuration>
hadoop-2.6.5/etc/hadoop/core-site.xml:</configuration>
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml:<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml:<configuration>
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml: The ACL is a comma-separated list of user and group names. The user and
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml: The ACL is a comma-separated list of user and group names. The user and
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml: The ACL is a comma-separated list of user and group names. The user and
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml: The ACL is a comma-separated list of user and group names. The user and
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml: The ACL is a comma-separated list of user and group names. The user and
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml: <description>ACL for AdminOperationsProtocol. Used for admin commands.
hadoop-2.6.5/etc/hadoop/hadoop-policy.xml: The ACL is a comma-separated list

相关文章


有用资源