Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and copy files with relative path

Tags:

linux

find

copy

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.


2 Answers

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
like image 151
Grapsus Avatar answered Sep 16 '25 03:09

Grapsus


@Grapsus had a good answer, but it didn't work for files with spaces in them. This one does :

find . -type f -exec bash -c 'path="{}"; d=/tmp/dest/$(dirname "$path"); mkdir -p "$d" ; cp "$path" "$d"' \;
like image 32
andrew lorien Avatar answered Sep 16 '25 03:09

andrew lorien