Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Copy named files recursively, preserving folder structure

Tags:

bash

shell

I was hoping:

cp -R src/prog.js images/icon.jpg /tmp/package 

would yield a symmetrical structure in the destination dir:

/tmp | +-- package     |     +-- src     |   |     |   +-- prog.js     |     +-- images         |         +-- icon.jpg 

but instead, both of the files are copied into /tmp/package. A flat copy. (This is on OSX).

Is there a simple bash function I can use to copy all files, including files specified by wildcard (e.g. src/*.js) into their rightful place within the destination directory. A bit like "for each file, run mkdir -p $(dirname "$file"); cp "$file" $(dirname "$file")", but perhaps a single command.

This is a relevant thread, which suggests it's not possible. The author's solution isn't so useful to me though, because I would like to simply provide a list of files, wildcard or not, and have all of them copied to the destination dir. IIRC MS-DOS xcopy does this, but there seems to be no equivalent for cp.

like image 531
mahemoff Avatar asked Oct 30 '09 14:10

mahemoff


People also ask

How do I copy a recursive folder?

In order to copy the content of a directory recursively, you have to use the “cp” command with the “-R” option and specify the source directory followed by a wildcard character.

How do I copy a directory structure in Linux?

Overview. We know we can copy a directory recursively using the cp command and the -R option. In this way, the source directory, together with all the files under it, will be copied to the destination.

What command do you use to copy files from all subdirectories to another directory?

To copy a directory with all subdirectories and files, use the cp command.

How copy all files and subdirectories in Linux?

Copying Directories with cp Command To copy a directory, including all its files and subdirectories, use the -R or -r option. The command above creates the destination directory and recursively copy all files and subdirectories from the source to the destination directory.


1 Answers

Have you tried using the --parents option? I don't know if OS X supports that, but that works on Linux.

cp --parents src/prog.js images/icon.jpg /tmp/package 

If that doesn't work on OS X, try

rsync -R src/prog.js images/icon.jpg /tmp/package 

as aif suggested.

like image 106
ustun Avatar answered Sep 17 '22 06:09

ustun