1

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 ?

4
  • Meaning all 3 files are copied somewhere else with their original directory names as prefixes or??? Commented May 20, 2016 at 9:36
  • you mean you want to merge all .txt files into one directory ? Commented May 20, 2016 at 9:49
  • yes, merge all .txt file into one directory. Commented May 20, 2016 at 9:59
  • 1
    If any of the existing answers solves your problem, please consider accepting it via the checkmark. Thank you! Commented Apr 23, 2017 at 12:45

3 Answers 3

3

Finally I can do this with cp from GNU coreutils and its --backup flag.

cp --backup=numbered */*.txt new_directory/ 
3
  • you have asked for merging content of all *.txt files into one Commented May 20, 2016 at 10:10
  • I've asked for merging content of folders (aka folder1, folder2, folder3) into on directory Commented May 20, 2016 at 10:24
  • you should have asked for "files of folder{1..3}" Commented May 20, 2016 at 10:26
1

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.

0

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.