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?
It is possible under most operating systems to create two files with the same name in different folders.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With