Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve directory tree while copying files with cp

I have about 1000 folders that I want to extract a single file from to upload to a server but I need to preserve the directory tree.

cp */myFile.txt ../newTree

Is what I basically want to do but instead of each file being saved to ../newTree/myFile.txt I want it to be ../newTree/*/myFile.txt where the * is the wildcard from the cp command.

I couldn't find a flag in the man file for this so I'm thinking I may need another utility besides cp

like image 965
Brad Dwyer Avatar asked Dec 16 '22 10:12

Brad Dwyer


1 Answers

With rsync:

find ./ -name myFile.txt -print0|rsync -0adv --files-from=- ./ ../newTree/

Without rsync:

You can find all files, for each file you create the directory in the newTree, and copy the file to it.

for file in */myFile.txt; do
    dir=$(dirname "$file")
    mkdir -p "../newTree/$dir"
    cp "$file" "../newTree/$dir"
done
like image 172
Arnaud Le Blanc Avatar answered Feb 12 '23 11:02

Arnaud Le Blanc