2017-04-26 66 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允许将这些作为记录分隔符。

相关问题