Shell – Using basename to strip file extension and search for files with the same name

filenamesfindshell-script

Basically, I have a folder /test/ that has a number of files of type .doc and .pdf. Some of the files have a .pdf and a .doc version, such as test.doc and test.pdf while others only have one version.

What I'm trying to do is find occurrences where there is a .doc and delete the corresponding .pdf using a script.

I've been tinkering with this line of code:

find /test/ -name "*.doc" - exec basename {} .doc \; -exec rm {}.pdf \;

However this returns the error that it cannot find files named example.doc.pdf instead of deleting the appropriately named .pdf from the find command. The reason I'm trying to do it this way is because there are .pdf files which don't have a matching .doc file which I do not wish to delete.

Best Answer

You can use this find command:

find /test/ -name "*.doc" -exec sh -c 'a="$1"; rm "${a%.doc}.pdf"' find-sh {} \;

It will search for .doc files in the directory /test/. For each found file a shell sh is called with the file as argument. ${a%.doc}.pdf replaces the file extension .doc with .pdf and rm removes it, if the file exists.

Related Question