Execute a command where a file is found

commandfindpath

How do I execute a command where a file is found?
Consider I've an directory named testdir that contains the following:

$ ls -R testdir/
testdir/:
dir1  dir2  dir3  dir4  dir5

testdir/dir1:
doc1.pdf

testdir/dir2:
file1.txt

testdir/dir3:
doc2.pdf

testdir/dir4:
file2.txt

testdir/dir5:
doc5.pdf

Now I want to perform an action (execute a command) where find finds a certain file/file type. For example let me find *.pdf:

$ find . -name '*.pdf'
./testdir/dir3/doc2.pdf
./testdir/dir5/doc5.pdf
./testdir/dir1/doc1.pdf

Now suppose I want to execute a command (for example say touch file) where the above command finds file(s). In other words, I want to create a file named file in each directory where at least one .pdf was found so that I get:

$ ls -R testdir/
testdir/:
dir1  dir2  dir3  dir4  dir5

testdir/dir1:
doc1.pdf  file

testdir/dir2:
file1.txt

testdir/dir3:
doc2.pdf  file

testdir/dir4:
file2.txt

testdir/dir5:
doc5.pdf  file

How do I accomplish such a work?
May be for every time file found, cd to where file exist and perform a command recursively.
I know that find has awesome feature: -exec but I can't get it to work.


This is only an example for getting an idea about what I want to do. Broadly: How to execute an command where file(s) are found (by find) recursively?

Best Answer

If you run this command your touch file will be run, potentially multiple times, from the directory in which the command has been started:

find -name '*.pdf' -exec touch file \;

On the other hand, if you run this variant, each instance of the command will be run in the target file's directory:

find -name '*.pdf' -execdir touch file \;

In both cases you can see this in action by substituting the touch file with either echo {} and/or pwd.


From manpage:

-execdir command ;
-execdir command {} +

    Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find.

Related Question