How Can I Merge Multiple Directories into One
18,658
Solution 1
Using find
+ xargs
+ mv
:
find . -type f -print0 | xargs -0 -I file mv --backup=numbered file .
This will move all the files in the current working directory and its subdirectories (recursively) into the current working directory, numbering files with the same filename numerically in order to avoid overwrites of files with the same filename.
Sample result on a tmp
folder with a 1
, 2
and 3
subfolders each containing a 1.ext
, 2.ext
and 3.ext
file:
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
Solution 2
If your directory structure looks like
dir root
- dir A
- file a
- file b
- dir B
- file c
- file d
and so on
you can do a simple
mv **/* .
to move all files at depth 1 to the root dir. Simple and Elegant!
Related videos on Youtube
Author by
Junior Cortez
Updated on September 18, 2022Comments
-
Junior Cortez almost 2 years
I have multiple files in multiple folders under one directory that need to be in one folder. Is there a command line that can help me accomplish this?
-
Admin about 9 yearsGive us some more hints..do you want to move all files in all subdirectories inside a directory?, or the directories are randomly located (how to find them?), do you want to move specific files or all of them inside the directories? also do you want to move them to a existing directory or a new directory?
-
Admin about 9 yearsI'm not sure how to make the question simpler, but I'll give it a shot. There are over 50 folders (all containing files) that I need merged into one.
-
Admin about 9 yearsAre these folders distributed randomly or under the same directory? if distributed randomly then do they contain a pattern in their names (how to find them)? if under the same directory then does the directory contain any other file/directory that needs to be excluded?
-
Admin about 9 yearsAll under one directory, no other files or folders to be excluded.
-
Admin over 6 years
-
-
Luc about 5 yearsDoes the double asterisk do anything different from a single one?
-
Trect almost 5 yearsrsync is much better
-
Cron Merdek over 4 yearsThis looks good, but I run into
mv: cannot move <PATH>: Directory not empty
-
Paul Rougieux almost 3 yearsTo keep the extension at the end (many programs use the extension to recognize files) you can rename the files in another step with:
rename 's/((?:\..+)?)\.~(\d+)~$/_$2$1/' *.~*~