如何對「locate」命令的結果採取行動?

如何對「locate」命令的結果採取行動?

我試圖找到'文件check_dns中定義的位置,儘管有很多文件。nagioscommands.cfg

我知道我可以運行類似find / -name "command.cfg" -exec grep check_dns {} \;搜尋匹配項的操作,但如果可能的話我想使用它,locate因為它是索引副本並且速度更快。

當我運行時,locate commands.cfg我得到以下結果:

/etc/nagios3/commands.cfg
/etc/nagiosgrapher/nagios3/commands.cfg
/usr/share/doc/nagios3-common/examples/commands.cfg
/usr/share/doc/nagios3-common/examples/template-object/commands.cfg
/usr/share/nagiosgrapher/debian/cfg/nagios3/commands.cfg
/var/lib/ucf/cache/:etc:nagiosgrapher:nagios3:commands.cfg

是否可以運行locate並將其通過管道傳輸到類似的內聯命令xargs或其他命令,以便我可以獲得grep每個結果?我意識到這可以透過 for 循環來完成,但我希望在這裡了解一些 bash-fu / shell-fu ,而不是如何針對這個特定情況執行此操作。

答案1

是的,你可以用xargs這個。

例如一個簡單的:

$ locate commands.cfg | xargs grep check_dns

(當grep看到多個文件時,它會在每個文件中進行搜尋並啟用匹配的文件名列印。)

或者您可以透過以下方式明確啟用檔案名稱列印:

$ locate commands.cfg | xargs grep -H check_dns

(以防萬一僅grep使用 1 個參數呼叫xargs

對於只接受一個檔案名稱參數的程式(與 不同grep),您可以限制提供的參數數量,如下所示:

$ locate commands.cfg | xargs -n1 grep check_dns

這不會列印符合行所在的文件的名稱。

結果相當於:

$ locate commands.cfg | xargs grep -h check_dns

使用現代的locate/xargs,您還可以防止空格問題:

$ locate -0 commands.cfg | xargs -0 grep -H check_dns

(預設情況下,空格分隔輸入xargs- 當您的檔案名稱包含空格時,這當然是一個問題...)

相關內容