【问题标题】:How to copy all the files with the same suffix to another directory? - Unix如何将具有相同后缀的所有文件复制到另一个目录? - Unix
【发布时间】:2013-06-24 22:47:40
【问题描述】:

我有一个目录,其中包含未知数量的子目录和未知级别的子*目录。如何将所有后缀相同的文件复制到新目录?

例如从这个目录:

> some-dir
  >> foo-subdir
    >>> bar-sudsubdir
      >>>> file-adx.txt
  >> foobar-subdir
    >>> file-kiv.txt

将所有 *.txt 文件移动到:

> new-dir
 >> file-adx.txt
 >> file-kiv.txt

【问题讨论】:

    标签: linux file unix copy find


    【解决方案1】:

    一种选择是使用find

    find some-dir -type f -name "*.txt" -exec cp \{\} new-dir \;
    

    find some-dir -type f -name "*.txt" 会在目录some-dir 中找到*.txt 文件。 -exec 选项为{} 表示的每个匹配文件构建一个命令行(例如cp file new.txt)。

    【讨论】:

    • 您能解释一下-exec 选项和多个斜杠`` 的含义吗?
    • 添加到上面。 {}; 已被转义。 ; 通常被 shell 视为命令分隔符。
    • 你不需要转义大括号。
    • 我知道。旧习惯很难改掉。
    【解决方案2】:

    使用findxargs 如下所示:

    find some-dir -type f -name "*.txt" -print0 | xargs -0 cp --target-directory=new-dir
    

    对于大量文件,此xargs 版本比使用find some-dir -type f -name "*.txt" -exec cp {} new-dir \; 更有效,因为xargs 将一次将多个文件传递给cp,而不是每个文件调用一次cp。所以xargs 版本的 fork/exec 调用会更少。

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2020-12-08
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多