2

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.

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
  • 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

1 Answers1

3

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 {}` \;

becomes

find /path/to/searchdir -name "file.rtf" -exec cp -v "/path/to/filetocopy.rtf" . \;
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • 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