2

On a unix server, I'm trying to figure out how to remove a file, say "example.xls", from any subdirectories that start with v0 ("v0*").

I have tried something like:

find . -name "v0*" -type d -exec find . -name "example.xls" -type f 
-exec rm {} \;

But i get errors. I have a solution but it works too well, i.e. it will delete the file in any subdirectory, regardless of it's name:

find . -type f -name "example.xls" -exec rm -f {} \;

Any ideas?

2 Answers 2

2

You will probably have to do it in two steps -- i.e. first find the directories, and then the files -- you can use xargs to make it in a single line, like

find . -name "v0*" -type d | \
   xargs -l -I[] \
       find [] -name "example.xls" -type f -exec rm {} \;

what it does, is first generating a list of viable directory name, and let xargs call the second find with the names locating the file name within that directory

Sign up to request clarification or add additional context in comments.

Comments

2

Try:

find -path '*/v0*/example.xls' -delete

This matches only files named example.xls which, somewhere in its path, has a parent directory name that starts with v0.

Note that since find offers -delete as an action, it is not necessary to invoke the external executable rm.

Example

Consider this directory structure:

$ find .
.
./a
./a/example.xls
./a/v0
./a/v0/b
./a/v0/b/example.xls
./a/v0/example.xls

We can identify files example.xls who have one of their parent directories named v0*:

$ find -path '*/v0*/example.xls'
./a/v0/b/example.xls
./a/v0/example.xls

To delete those files:

find -path '*/v0*/example.xls' -delete

Alternative: find only those files directly under directory v0*

find -regex '.*/v0[^/]*/example.xls'

Using the above directory structure, this approach returns one file:

$ find -regex '.*/v0[^/]*/example.xls'
./a/v0/example.xls

To delete such files:

find -regex '.*/v0[^/]*/example.xls' -delete

Compatibility

Although my tests were performed with GNU find, both -regex and -path are required by POSIX and also supported by OSX.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.