-1

I am looking to create a simple script that does the following:

cd /specified/directory
cd into child directory only if it has a 4 digit name e.g 1234
rm -r all files that begin with letter P
rm -r all files that begin with letter E
exit child directory
check for next directory with 4 digit number
repeat task
End
2

It is possible that you will exhaust environment space with a vast number of files allowing filename expansion to do the job (esp. on some UNIX systems). For this reason I would use 'find' to determine the files you wish to delete.

To see the files that will be deleted you could run:

find $(find /specified/directory -d -name "[0-9][0-9][0-9][0-9]") -name "[E|P]*" -print 

to delete them you can extend this with the -exec option

find $(find /specified/directory -d -name "[0-9][0-9][0-9][0-9]") -name "[E|P]*" -exec rm -i {} \;
  • Is that find command nested? Is that how it's working? Just trying to figure it out, I understand the rest. Thank you for the advice – eekfonky Jul 22 '15 at 22:40
  • I have now been asked only to remove files that are older than 7 days. Can I incorporate an -mtime 7 command into this statement? – eekfonky Jul 23 '15 at 13:17
  • The find is nested. The inner 'find' determines the directories to examine. find /specified/directory -d -name "[0-9][0-9][0-9][0-9]". The output from this then feeds the outer find, which searches for the files. Yes you can add any other find options to either the inner or outer statement as necessary – Simon Jul 24 '15 at 19:45
2

You don't need a loop or a scirpt for that; let filename expansion do that job:

rm /specified/directory/[0-9][0-9][0-9][0-9]/{P,E}*

This matches all files within a subdirectory with 4 digits as name in the directory /specified/directory and a filename that starts with P or E.

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.