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


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

使用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

更新于:2020年2月25日

2K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告