I'd like to merge the content of these folders with a command line.
. ├── folder1 │ │ file.txt │ ├── folder2 │ │ file.txt │ └───folder3 │ file.txt How can I do this ?
Finally I can do this with cp from GNU coreutils and its --backup flag.
cp --backup=numbered */*.txt new_directory/ *.txt files into one folder{1..3}" The following command-line loop will copy the (top-level) contents of every folder named "folder*" in your current directory into a directory named "new_directory". The /* glob will, by default, not match "dot files"; use shopt -s dotglob if you want to change that behavior. If the same (base) filename already exists in new_directory, then it prefixes the destination file with the originating folder (and an underscore), in order to make it unique.
All in one line:
for f in folder*/*; do [ ! -e "new_directory/$(basename "$f")" ] && { cp "$f" new_directory/; continue; }; [ -e "new_directory/$(basename "$f")" ] && cp "$f" "new_directory/$(dirname "$f")_$(basename "$f")"; done Broken out for readability:
for f in folder*/* do [ ! -e "new_directory/$(basename "$f")" ] && { cp "$f" new_directory/; continue; } [ -e "new_directory/$(basename "$f")" ] && cp "$f" "new_directory/$(dirname "$f")_$(basename "$f")" done If you intent instead to move the files from their original locations, simply change the cp's to mv's.
Thank you @Ghilas Belhadj ! One could end up here trying to do that: copy all files from a file hierarchy to a unique directory, knowing some files may have the same name (ie: files which differ only by their absolute name):
find /dir1 -type f -exec cp "{}" --backup=numbered /dir2 \; But I don’t know if it works with mv.
NB: it does not bother with file content in any way, but if there are a /dir1/foo/name and a /dir1/bar/name it will end up with /dir2/name and /dir2/name~1~ and so on.
.txtfiles into one directory ?