如何将多个目录合并为一个
我在一个目录下的多个文件夹中有多个文件,需要在一个文件夹中。 是否有命令行可以帮助我实现这一目标?
使用find
+ xargs
+ mv
:
find . -type f -print0 | xargs -0 -I file mv --backup=numbered file .
这会将当前工作目录及其子目录中的所有文件(递归地)移动到当前工作目录中,以数字方式对具有相同文件名的文件进行编号,以避免覆盖具有相同文件名的文件。
在tmp
文件夹上的示例结果,该文件夹包含2
和3
3.ext
文件夹,每个子文件夹包含1.ext
, 2.ext
和3.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.