簡體   English   中英

命令行遞歸搜索目錄中所有文本文件中的所有文件

[英]Command line to search all files in all text files in directory recursively

我剛剛遷移到 Octopress。 在遷移過程中,該插件從 WordPress 下載了很多未使用的圖像,現在我正在嘗試將其刪除。

我想列出所有圖像並搜索_post文件夾中的所有文件,並給我所有未使用的文件,以便我可以刪除它們。

我想出了這個命令。

find ./ -type f | xargs basename | xargs grep -r {} ../_posts/

我認為這是不正確的。 它給了我這個結果。

grep: Screenshot-2015-07-30-13.04.35.png: No such file or directory
grep: Screenshot-2015-07-30-13.05.41-150x116.png: No such file or directory
grep: Screenshot-2015-07-30-13.05.41.png: No such file or directory
grep: Screenshot-2015-07-30-13.06.33-150x150.png: No such file or directory
grep: Screenshot-2015-07-30-13.06.33-231x300.png: No such file or directory
grep: Screenshot-2015-07-30-13.06.33-518x500.png: No such file or directory
grep: Screenshot-2015-07-30-13.06.33-518x592.png: No such file or directory
grep: Screenshot-2015-07-30-13.06.33.png: No such file or directory
grep: Screenshot-2015-07-30-13.07.47-1024x601.png: No such file or directory
grep: Screenshot-2015-07-30-13.07.47-1120x500.png: No such file or directory
grep: Screenshot-2015-07-30-13.07.47-150x150.png: No such file or directory
grep: Screenshot-2015-07-30-13.07.47-300x176.png: No such file or directory
grep: Screenshot-2015-07-30-13.07.47-786x592.png: No such file or directory
grep: Screenshot-2015-07-30-13.07.47.png: No such file or directory

因為即使是正在使用的文件仍然會被列出。

那是因為您沒有限制xargs拾取的行數

find ./ -type f | xargs basename | xargs grep -r {} ../_posts/

xargs 會生成帶有許多字符串的 grep,你會得到

grep -r foo bar baz qux ../_posts/

並且由於 grep 只需要一種模式,因此所有其他模式都被假定為文件名。

快速修復是

find ./ -type f | xargs -L 1 basename | xargs -L 1 grep -r {} ../_posts/

我會在沒有 xargs 的情況下重寫它:

find ./ -type f -printf "%f\n" | grep -rFf - ../_posts/

這樣,您會得到一個 find 調用和一個 grep 調用。 應該會快很多。


由於grep -f -不起作用,更復雜的 bash 進程替換(請參閱您的 bash 手冊頁)

grep -rFf <(find ./ -type f -exec basename '{}' \;) ../_posts/

這會將find輸出轉換為grep可以使用-f選項讀取的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM