代码之家  ›  专栏  ›  技术社区  ›  illus

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

  •  0
  • illus  · 技术社区  · 7 年前

    我想列出嵌套目录中的所有文件,但在该目录中有一些文件的名称中有空格。我想写下哪些文件名中没有空格,哪些文件名中有空格。

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

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

    我想要这样的东西:

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

    提前谢谢你。

    2 回复  |  直到 7 年前
        1
  •  0
  •   tripleee    7 年前

    你可以在摘要中列出一个条件 -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 ... 剧本(下划线用于填充 $0 子shell中有一些东西。)

    如果目录树不是太深,那么运行起来可能会容易得多 find 两次

    find "$path" -type f -name '* *' >a.txt
    find "$path" -type f \! -name '* *' >b.txt
    
        2
  •  0
  •   Barmar    7 年前

    使用两个单独的命令:

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