1

I use the following command to find a file and copy it somewhere else,

find /search/ -name file.txt -exec cp -Rp {} /destination \;

How can I copy all files and subdirectories in the parent directory of file.txt?

Example,

/search/test/sub
/search/test/sub2
/search/test/file.txt
/search/test/file.doc

They should be copied as

/destination/sub
/destination/sub2
/destination/file.txt
/destination/file.doc

1 Answer 1

3

With -execdir (not a standard predicate, but often implemented), the given utility would execute in the directory where the file was found.

This means that you could do

find /search -name file.txt -execdir cp -Rp . /destination \;

Without -execdir:

find /search -name file.txt -exec sh -c 'cp -Rp "${1%/*}/." /destination' sh {} \;

or,

find /search -name file.txt -exec sh -c 'cd "${1%/*}" && cp -Rp . /destination' sh {} \;

These last two variations execute a short in-line script for each found file. The script takes the pathname of the file as its first argument (in $1), and strips the filename off of the pathname using ${1%/*} (a standard parameter substitution). Then it applies the same cp command as in the first variation with -execdir.

The code that does the cd emulates a bit more faithfully what the -execdir variation at the top actually does, while the middle variation bypasses changing the directory by referring to . in the source directory at the end of the path instead.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .