如何将多个目录合并为一个

我在一个目录下的多个文件夹中有多个文件,需要在一个文件夹中。 是否有命令行可以帮助我实现这一目标?

使用find + xargs + mv

 find . -type f -print0 | xargs -0 -I file mv --backup=numbered file . 

这会将当前工作目录及其子目录中的所有文件(递归地)移动到当前工作目录中,以数字方式对具有相同文件名的文件进行编号,以避免覆盖具有相同文件名的文件。

tmp文件夹上的示例结果,该文件夹包含23 3.ext文件夹,每个子文件夹包含1.ext2.ext3.ext文件:

 ubuntu@ubuntu:~/tmp$ tree . ├── 1 │  ├── 1.ext │  ├── 2.ext │  └── 3.ext ├── 2 │  ├── 1.ext │  ├── 2.ext │  └── 3.ext └── 3 ├── 1.ext ├── 2.ext └── 3.ext 3 directories, 9 files ubuntu@ubuntu:~/tmp$ find . -type f -print0 | xargs -0 -I file mv --backup=numbered file . ubuntu@ubuntu:~/tmp$ tree . ├── 1 ├── 1.ext ├── 1.ext.~1~ ├── 1.ext.~2~ ├── 2 ├── 2.ext ├── 2.ext.~1~ ├── 2.ext.~2~ ├── 3 ├── 3.ext ├── 3.ext.~1~ └── 3.ext.~2~ 3 directories, 9 files 

您可以使用find执行此操作:

 find . -type f -exec mv -i -t new_dir {} + 

首先创建要移动所有文件的目录( mkdir new_dir ),这里我们将移动./new_dir目录中的所有文件。

  • find . -type f find . -type f将找到当前目录下所有目录下的所有文件,因此你需要cd进入包含所有子目录的目录,或者你可以使用绝对路径,例如~/foo/bar

  • find-exec谓词将执行mv命令,该命令将find所有文件到new_dir目录。 您可以再次使用绝对路径。

  • mv -i会在覆盖文件之前提示您。

如果新目录位于其他位置,请使用绝对路径:

 find ~/path/to/dir -type f -exec mv -i -t ~/path/to/new_dir {} + 

你可以使用命令:

 find . -type f -execdir mv '{}' /parent-dir \; 

man find

  -execdir utility [argument ...] ; The -execdir primary is identical to the -exec primary with the exception that utility will be executed from the directory that holds the current file. The filename substituted for the string ``{}'' is not qualified.