如何修改 find 函数循环来处理反斜杠和空格?

use*_*627 2 bash

目前,我正在尝试解析目录中的所有文件。我有一个 find 函数,但它似乎无法将带有空格的文件目录解析为循环。这"$DIR"是我希望搜索的目录。有没有人知道如何修改它以使其工作?谢谢。

for file in $(find "$DIR" -type f)
do
   echo "$file"
done
Run Code Online (Sandbox Code Playgroud)

Dop*_*oti 5

你不需要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)


gle*_*man 5

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)

很多东西要在那里解压:

  • 我们使用Process Substitution来执行 find 命令,并且能够像读取文件一样读取结果。
  • 要逐字读取一行输入,bash 习惯用法是IFS= read -r line. 这允许将任意空格和反斜杠读入变量。
  • read -d ''使用空字节(由 产生-print0)作为行尾字符而不是换行符。