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?
5 Answers
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
- 41,268
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!
- 151
- 1
- 4
You can do this using find:
find . -type f -exec mv -i -t new_dir {} +
At first create the directory (mkdir new_dir) where you want to move all the files, here we are moving all the files in the ./new_dir directory.
find . -type fwill find all the files under all the directories under the current directory, so you need tocdinto the directory that contains all the subdirectories or you can use the absolute path e.g.~/foo/barThe
-execpredicate offindwill execute themvcommand that will move all the files found to thenew_dirdirectory. Once again you can use the absolute path.mv -iwill prompt you before overwriting a file.
If the new directory is located elsewhere, use absolute paths:
find ~/path/to/dir -type f -exec mv -i -t ~/path/to/new_dir {} +
- 93,925
find /path/to/root/directory -type f -exec mv {} /path/to/destination/folder/ \;
Let's break down the command and understand each part:
find: The command used to search for files and directories within a specified location./path/to/root/directory: Replace this with the actual path to your root directory where the subdirectories are located.-type f: Specifies that we are looking for regular files (not directories).-exec mv {} /path/to/destination/folder/ \;: Executes the mv command on each found file ({}). It moves (mv) each file to the specified destination folder (/path/to/destination/folder/).
- 101
you can use the command:
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.
- 87,123