2017-04-26 85 views
1

有一個腳本,看起來像這樣:我如何找到目錄中的所有文件路徑使用bash

function main() { 
    for source in "[email protected]"; do 
    sort_imports "${source}" 
    done 
} 

main "[email protected]" 

現在如果我通過在./myFile.m腳本按預期工作的文件。

我想將其更改爲傳入./myClassPackage,並讓它找到所有文件並在它們每個上調用sort_imports。

我想:

for source in $(find "[email protected]"); do 
    sort_imports "${source}" 
    done 

,但是當我把它稱爲我得到我傳遞一個目錄中的錯誤。

+0

你爲什麼不分配找到「$ @」的東西和分析的結果是什麼呢? – ergonaut

+0

爲什麼不告訴'find'只發現文件? –

回答

1

如果你不想做find枚舉目錄,然後排除他們:

for source in $(find "[email protected]" -not -type d); do 
sort_imports "${source}" 
done 
+0

這工作很好,謝謝! – Tai

+0

要限制爲*文件*而不是*所有不是目錄*,您可以使用'find「$ @」-type f' –

+0

@ DavidC.Rankin是的,這是更好的解決方案 – Tai

3

使用命令替換的輸出爲for循環有因分詞的陷阱。一個真正堅如磐石的解決方案將使用空字節分隔符來正確處理名稱中帶有換行符的文件(這不常見,但有效)。

假設你只需要常規文件(而不是目錄),試試這個:

while IFS= read -r -d '' source; do 
    sort_imports "$source" 
done < <(find "[email protected]" -type f -print0) 

-print0選項使find與空字節單獨的條目,而-d ''選項read允許將這些作爲記錄分隔符。

相關問題