BASH: 如果条件使用 find 命令的结果来确定将写入哪个文件

BASH: If condition uses result from find command to determine which file will be written

我想列出嵌套目录中的所有文件,但该目录中有一些文件名称中包含 space。所以我想写下哪些文件的路径在它们的名称中没有 space,哪些在 2 个不同的文件中。

到目前为止,我只知道如何通过这个命令找到名字中有space的人:

find /<my directory> -type f -name * *

我想要这样的东西:

find /<my directory> -type f
   if [ name has space]
   then > a.txt
   else > b.txt
   fi

提前致谢。

你可以把一个条件放在一个简短的-exec中。这比您希望的要复杂一些,因为 -exec 不能直接包含 shell 内置函数。

find "$path" -type f -exec sh -c 'for f; do
    case $f in *\ *) dest=a;; *) dest=b;; esac;
    echo "$f" >>$dest.txt
  done' _ {} +

也就是说,将找到的文件传递给下面的sh -c ...脚本。 (下划线是用subshell里面的东西填充[=15=]。)

如果目录树不是太深,也许 运行 find 两次会容易很多。

find "$path" -type f -name '* *' >a.txt
find "$path" -type f \! -name '* *' >b.txt

使用两个单独的命令:

find "$path" -type f -name '* *' > a.txt
find "$path" -type f -not -name '* *' > b.txt