This question already has an answer here:

I'm trying to create a script which will find files of a certain filename, copy a file to that file's location, and then delete the found file.

Ignoring the delete part for now, this is what I have so far:

find /path/to/searchdir -name "file.rtf" -exec cp -v "/path/to/filetocopy.rtf" `dirname {}` \;

Unfortunately I can't seem to get it to evaluate the dirname properly, as it returns "." for any instances of the file that it finds.

marked as duplicate by Gilles, Satō Katsura, Michael Homer, countermode, Kusalananda Jan 25 '17 at 8:28

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    I think it's because you're trying to use the {} macro inside of a subshell, which I don't reckon will work. – DopeGhoti Jan 24 '17 at 21:50

find's -execdir action seems more appropriate:

find /path/to/searchdir -name file.rtf -execdir cp -v /path/to/filetocopy.rtf . \;

This will run the cp from every directory found containing a file named file.rtf, so . as seen by cp will be the appropriate directory every time cp is run.

You can then add -delete to delete the file (after checking everything works).

The reason your approach isn't working is that the shell evaluates dirname {} before running find, and dirname {} outputs .. So

find /path/to/searchdir -name "file.rtf" -exec cp -v "/path/to/filetocopy.rtf" `dirname {}` \;


find /path/to/searchdir -name "file.rtf" -exec cp -v "/path/to/filetocopy.rtf" . \;
  • Awesome, I didn't know about the execdir option which is much more appropriate here. Also didn't know about the order of operations but that makes sense. Thanks for the help! – user2509899 Jan 25 '17 at 16:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.