Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

bash

unix

copy

I have a question about unix command line. I have many files like these:

/f/f1/file.txt

/f/f2/file.txt

/f/f3/file.txt

and so on.

I had like copy all file.txt with their father folder in another folder g like:

/g/f1/file.txt

/g/f2/file.txt

/g/f3/file.txt

I can't copy all content of folder f because in each sub-folder f1, f2, ... I have many other files that I don't want copy.

How could I do this with the command line? Eventually using a bash script?

like image 746
fibon82 Avatar asked Jan 26 '12 16:01

fibon82


People also ask

Can you have 2 files with the same name in different folders?

It is possible under most operating systems to create two files with the same name in different folders.

How can I copy the contents of a folder to another folder in a different directory using terminal?

Answer: Use the cp Command You can use the cp command to copy files locally from one directory to another. The -a option copy files recursively, while preserving the file attributes such as timestamp. The period symbol ( . ) at end of the source path allows to copy all files and folders, including hidden ones.

How do you copy the contents of a folder to another folder?

Alternatively, right-click the folder, select Show more options and then Copy. In Windows 10 and earlier versions, right-click the folder and select Copy, or click Edit and then Copy. Navigate to the location where you want to place the folder and all its contents.


2 Answers

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.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
like image 116
jaypal singh Avatar answered Oct 06 '22 20:10

jaypal singh


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

kent$  tree t g
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
like image 32
Kent Avatar answered Oct 06 '22 22:10

Kent