shell for loop with find 文件名包含空格

Mat*_*nco 1 find shell-script filenames whitespace

考虑一个具有典型 Microsoft Windows 文件名的目录:

新建文档.txt
文件
Foo - Copy.doc

我想对每个文件做一些事情,例如:

对于 $(find ${POLLDIR} -type f -mmin +1 -print0) 中的 sendfile
做
  回声 \"${sendfile}\"
  ls -l "${sendfile}"
  等等
  如果成功_以上
  然后
    mv "${sendfile}" "${donedir}/."
  菲
完毕

请注意,我不想只以“${sendfile}”作为参数运行 1 个命令。我需要循环来做错误检查和其他事情(比如在成功时移动“${sendfile}”并在失败时登录)。

什么是从 find 转义/引用文件名的“正确”构造,以便我可以在ls上面的命令中使用它们?如果可能,我想避免将文件名一一存储在临时文件中。

我不认为find -printf '"%p"\n'正如三重奏在对问题[当文件名包含空格时如何使用查找?] 将在for foo in $(...) do构造中工作。

我认为?在这种情况下替换“非法”字符对我有用,但这会非常难看。for 循环最终处理 ${POLLDIR} 中的文件,然后在完成后移动它们,因此“Foo bar.txt”与“Foo-bar.txt”冲突的机会为 0 (-ish)。

到目前为止,我最好的尝试是:

对于 $(find ${POLLDIR} -type f -mmin +1 -print | tr ' ' '?') 中的 sendfile
做
  ...
完毕

有没有更清洁的建议?

jim*_*mij 10

使用find ... -print0 | while IFS="" read -d ""构造:

find "${POLLDIR}" -type f -mmin +1 -print0 | while IFS="" read -r -d "" sendfile
  do
    echo "${sendfile}"
    ls -l "${sendfile}"
    and-so-on
    if success_above
      then
        mv "${sendfile}" "${donedir}/."
    fi
done
Run Code Online (Sandbox Code Playgroud)

-d ""行尾字符设置为 null ( \0),这是分隔找到的每个文件名的原因,find ... -print0并且IFS=""还需要处理包含换行符的文件名 - 根据 POSIX,仅禁止使用斜杠 ( /) 和 null ( \0)。这-r确保反斜杠不转义字符(以便\t例如实际反斜杠后跟一个相匹配t,而不是一个选项卡)。

  • 这是一场完美的比赛。我已经忘记了`read -d`。谢谢! (2认同)