-1

to delete files on under folder we can use the following approach with find

find /home -type f -delete

but how to delete recursive only the files that exists under temp folder ?

lets say we have the following example of temp path

/home/bla/bla/temp
/home/test/temp
/home/subf/subf/subf/temp
.
.
.
/home/1/temp

how to change the find syntax in order to delete only the files under temp directory

the target is to use find command in order to match only the temp folders and remove the files under temp directory

3
  • So you want to delete all files inside any directory named temp, but not the directory itself? Please confirm. -type f in your example matches regular files, but you keep saying "files". This is a broad term. Do you really mean (all) files? or regular files? Removing regular files only will leave directories, symlinks, sockets and such intact. Please edit the question and clarify. Jul 3 at 9:26
  • I answered the question according to my interpretation of it. If you clarify (see my first comment) and the answer needs to be adjusted to the new interpretation then I will adjust it. Jul 3 at 10:09
  • Please do not cross-post. For the record, the other copy is on Unix & Linux SE. Jul 3 at 15:57

1 Answer 1

3

The following command will find regular files in any directory named temp and below, below /home.

find /home -type f -path '*/temp/*'

To actually delete them:

find /home -type f -path '*/temp/*' -delete

Notes:

  • By default find does not follow symlinks. See man 1 find for options -L, -H and (if supported) -P.

  • -delete is not portable. If your find does not support -delete, use -exec rm {} +. -delete is better not only because it doesn't create an additional process. It is safer as it (at least -delete implemented in GNU find) removes the race condition where someone may be able to make you remove the wrong file(s) by changing some directory to a symlink in-between the time find finds a file and rm removes it. The fact our find command does not follow symlinks is irrelevant at this point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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