Delete File from Directories

Hi All,
I am trying to delete Files from a directory using the below command
find $/test/abc/xyz -mtime +30 -exec rm -f {} \;
The above command is deleting the files more than 30 days.
The problem is there are some subdirectories in xyz,
when i execute the above command its trying to delete the direcotires as well,
however its not having permission to do so, its giving an error saying
"No permission to delete the direcotry", So i am saved.
Is there a way i can exculde touching the directories and just delete the files.
Thanks in advance

If I read your question correctly, you have files in the subdirectories that you do want to be deleted, but don't want to try to remove the directories themselves. If that is correct then try:

find $/test/abc/xyz -type f -mtime +30 -exec rm -f {} \;

which will only result in a true evaluation if the file is a regular file.

If you don't want to remove files in any directory below the current directory you'll need to add other options to the find.

Regardless, before running commands which remove things, it's always good form to test it with a harmless command:

find $/test/abc/xyz -type f -mtime +30 -exec echo rm -f {} \;

Shows you what the command would do and if you are sure that the command will only delete the things you want removed, then you can remove the echo and execute the command. This practice has saved my butt many times from having to recover files from backup because I fat fingered something in the command.

1 Like

Hi agama, Thanks a lot for your response....

---------- Post updated at 02:45 PM ---------- Previous update was at 10:02 AM ----------

when i am trying the below command

find /test/abc/xyx -type f -mtime +7 -exec rm -f {} \;

there are some subfolders in xyx for which i don't have permission to delete.

How do i exclude them.

If the number of directories is small, you can hard code them with the prune option which will skip processing the directories and their contents. This example does not do anything with files in the foo or bar directories:

find .  -name foo -prune -o -name bar -prune -o -type f -exec echo rm {} \;

If you have more than a couple, you may be better off using the -group or -user flags to control which files are deleted. Check out the manual page for find -- it has useful examples and lists all of your options.