copy many files (same name) contained in different father folder copy many files (same name) contained in different father folder unix unix

copy many files (same name) contained in different father folder


Manual for cp shows this option -

--parents              use full source file name under DIRECTORY

So if you are on bash v4 you can do something like this -

[jaypal:~/Temp/f] tree.├── f1│   ├── file.txt  # copy this file only with parent directory f1│   ├── file1.txt│   └── file2.txt└── f2    ├── file.txt  # copy this file only with parent directory f2    ├── file1.txt    └── file2.txt2 directories, 6 files[jaypal:~/Temp/f] mkdir ../g[jaypal:~/Temp/f] shopt -s globstar[jaypal:~/Temp/f] for file in ./**/file.txt; do cp --parents "$file" ../g ; done[jaypal:~/Temp/f] tree ../g../g├── f1│   └── file.txt└── f2    └── file.txt2 directories, 2 files


tar is sometimes helpful for coping files: see the small test:

kent$  tree t gt|-- t1|   |-- file|   `-- foo ---->####this file we won't copy|-- t2|   `-- file`-- t3    `-- fileg3 directories, 4 fileskent$  cd tkent$  find -name "file"|xargs tar -cf - | tar -xf - -C ../gkent$  tree ../t ../g../t|-- t1|   |-- file|   `-- foo|-- t2|   `-- file`-- t3    `-- file../g|-- t1|   `-- file|-- t2|   `-- file`-- t3    `-- file


Take a look at rsync. Assuming you are in '/',

rsync -r f/ g/ --include "*/" --include "*/file.txt" --exclude "*"

The first include is necessary to tell rsync to look inside the subdirectories (and counteract the last exclude). The second include selects the files you want to copy. The exclude makes sure that other files are not processed in /f that are not of the required pattern.

Note: in case you have symbolic links, rsync will copy the link and not the file the link points to, unless you specify --copy-links.

Example:

$ find f g -type ff/f1/file.txtf/f1/fileNew.txtf/f2/file.txtf/f3/file.txtfind: g: No such file or directory$ rsync -r f/ g/ --include "*/" --include "*/file.txt" --exclude "*"$ find f g -type ff/f1/file.txtf/f1/fileNew.txtf/f2/file.txtf/f3/file.txtg/f1/file.txtg/f2/file.txtg/f3/file.txt