How can I copy a single file and maintain directory structure?

12

7

How can I do this on the command line?

e.g. copy /dir/another/file to /tmp/ so I have /tmp/dir/another/file

Allan Thomas

Posted 2012-07-25T14:08:55.310

Reputation: 313

Answers

25

cp --parents /dir/another/file /tmp

will do exactly what you want.

Colin 't Hart

Posted 2012-07-25T14:08:55.310

Reputation: 564

any ideas for os/x? --parents do not live here ;( – javadba – 2018-03-27T02:29:29.810

tar or rsync? See the other two answers :-) – Colin 't Hart – 2018-04-26T07:24:01.743

1For macOS you can, via homebrew, install brew install coreutils and use gcp --parents /dir/another/file /tmp – dotnetCarpenter – 2019-02-27T13:42:04.353

4

rsync can be a good help for this :

rsync -Ravz my/first/dir/file.txt another_dir

will gave as result

another_dir/my/first/dir/file.txt

Cédric Julien

Posted 2012-07-25T14:08:55.310

Reputation: 604

2

You can use tar to preserve paths while copying files:

tar cf - /dir/another/file | (cd /tmp && tar xf -)

Roland Levillain

Posted 2012-07-25T14:08:55.310

Reputation: 121