I'd like to merge the content of these folders with a command line.

├── folder1
│   │ file.txt
├── folder2
│   │ file.txt
    │ file.txt

How can I do this ?

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

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

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

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*/*
  [ ! -e "new_directory/$(basename "$f")" ] && { cp "$f" new_directory/; continue; }
  [ -e "new_directory/$(basename "$f")" ] && cp "$f" "new_directory/$(dirname "$f")_$(basename "$f")"

If you intent instead to move the files from their original locations, simply change the cp's to mv's.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.