目前,我正在尝试解析目录中的所有文件。我有一个 find 函数,但它似乎无法将带有空格的文件目录解析为循环。这"$DIR"
是我希望搜索的目录。有没有人知道如何修改它以使其工作?谢谢。
for file in $(find "$DIR" -type f)
do
echo "$file"
done
Run Code Online (Sandbox Code Playgroud)
你不需要for
循环这个。
find "$dir" -type f
Run Code Online (Sandbox Code Playgroud)
默认情况下将输出所有找到的对象。
您可以通过以下方式明确说明:
find "$dir" -type f -print
Run Code Online (Sandbox Code Playgroud)
如果您真的想遍历这些,请使用空分隔符和xargs
:
find "$dir" -type f -print0 | xargs -0 -n1 echo
Run Code Online (Sandbox Code Playgroud)
或者find
自己的-exec
:
find "$dir" -type f -exec echo "{}" \;
Run Code Online (Sandbox Code Playgroud)
find ... | xargs ...
并且find ... -exec ...
都是比这更好的选择:要使用 shell 循环正确迭代查找结果,我们必须使用while read
循环:
while IFS= read -d '' -r filename; do
echo "$filename"
done < <(find "$dir" -type f -print0)
Run Code Online (Sandbox Code Playgroud)
很多东西要在那里解压:
IFS= read -r line
. 这允许将任意空格和反斜杠读入变量。read -d ''
使用空字节(由 产生-print0
)作为行尾字符而不是换行符。