如何在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+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告