Copy many files (same name) contained in another father folder

Hi guys, I have a question about the unix command line. I have many such files:

/f/f1/file.txt /f/f2/file.txt /f/f3/file.txt and so on... 

I would like to copy all file.txt using the father folder in another g folder , for example:

 /g/f1/file.txt /g/f2/file.txt /g/f3/file.txt 

I cannot copy all the contents of folder f , because in each sub-folder f1, f2, ... I have many other files that I do not want to copy.

How can I do this using the command line? After all, using a bash script?

Thanks!

+4
source share
4 answers

The manual for cp displays 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.txt 2 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.txt 2 directories, 2 files 
+6
source

tar is sometimes useful for copying files: see a little test:

 kent$ tree tg t |-- t1 | |-- file | `-- foo ---->####this file we won't copy |-- t2 | `-- file `-- t3 `-- file g 3 directories, 4 files kent$ cd t kent$ find -name "file"|xargs tar -cf - | tar -xf - -C ../g kent$ tree ../t ../g ../t |-- t1 | |-- file | `-- foo |-- t2 | `-- file `-- t3 `-- file ../g |-- t1 | `-- file |-- t2 | `-- file `-- t3 `-- file 
+2
source

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

 rsync -rf/ g/ --include "*/" --include "*/file.txt" --exclude "*" 

First of all, you need to specify rsync for viewing inside subdirectories (and counteract the last exception). The second involves selecting the files you want to copy. An exclude ensures that other files are not processed in / f, which do not have the required template.

Note. If you have symbolic links, rsync will copy the link, not the file the link points to, unless you specify --copy-links .

Example:

 $ find fg -type f f/f1/file.txt f/f1/fileNew.txt f/f2/file.txt f/f3/file.txt find: g: No such file or directory $ rsync -rf/ g/ --include "*/" --include "*/file.txt" --exclude "*" $ find fg -type f f/f1/file.txt f/f1/fileNew.txt f/f2/file.txt f/f3/file.txt g/f1/file.txt g/f2/file.txt g/f3/file.txt 
+2
source

This seems to help you:

 find /f/ -name file.txt -execdir cp -R . /g/ \; 

It finds all the files with the name file.txt in the / f / directory, and then, using execdir (which runs in the directory containing the associated file), copies the directory containing the file to the / g / directory.

+1
source

Source: https://habr.com/ru/post/1393213/


All Articles