Find and copy files with relative path

copy, find, linux

Solution

Here you go:

$ tree
.   
├── a
│   └── foo
└── b
    └── foo

2 directories, 2 files
$ find . -type f -exec bash -c 'path={}; d=/tmp/dest/$(dirname $path); mkdir -p $d ; cp $path $d' \;
$ tree /tmp/dest/
/tmp/dest/
├── a
│   └── foo
└── b
    └── foo

2 directories, 2 files

Problem

At this Stackoverflow question, it shows how to copy files and it will recurse into subdirectories to copy files. How do I copy files and include the relative path in the copy? For instance, `find /path/to/directory/or/just/dot -name '*somepartoffilename*' -exec cp {} /path/you/want/to/copy/to \;` So if you have `/path/to/directory/a/somepartoffilename.txt` and `/path/to/directory/b/somepartoffilename.txt`, you'll only end up with one of those files in `/path/you/want/to/copy/to`.

Original source