将查找与循环一起使用,返回名称中包含空格的文件

using find with a loop returning files with spaces in their names

在 Windows10 上使用 Cygwin,我试图在一个目录 (dir1) 中查找不在另一个目录 (dir2) 中的文件,而不管文件路径如何

想法是遍历 dir1 中的所有文件,并针对每个文件在 dir2 中启动查找命令并仅显示丢失的文件:

for f in `ls -R /path/to/dir1` ; do
  if [ $( find /path/to/dir2 -name "$f" | wc -l ) == 0 ] ; then
    echo $f
  fi
done

问题是一些文件名中有空格,这导致查找命令失败

有什么想法吗?

你能用 findcomm 做这个吗?类似下面的内容应该打印 dir1 中不在 dir2.

中的文件
comm -23 <(find dir1 -type f -printf '%f\n' | sort -u) <(find dir2 -type f -printf '%f\n' | sort -u)

它也适用于空格:

$ mkdir dir1 dir2
$ touch dir1/foo dir1/bar
$ touch dir2/foo dir2/baz
$ touch dir1/'foo bar'
$ comm -23 <(find dir1 -type f -printf '%f\n' | sort -u) <(find dir2 -type f -printf '%f\n' | sort -u)
./bar
./foo bar

为了真正的安全,您应该使用以 NUL 结尾的字符串,这样带有换行符的文件名就可以了。

comm -z23 <(find dir1 -type f -printf '%f[=12=]' | sort -uz) <(find dir2 -type f -printf '%f[=12=]' | sort -uz) | xargs -0 printf '%s\n'