Home > database >  Delete filetype only if the path includes a specific string
Delete filetype only if the path includes a specific string

Time:03-11

I'm scratching my head trying to figure this one out.

We have a certain filetype that exists on disk (*.sc) that I'd like to remove but ONLY if the preceding folder path has the name "cache" in it.

 /jobs/job1/files/myfile.sc - Will NOT be deleted
 /jobs/job1/cache/myfile.sc - Will be deleted

To further complicate matters cache can appear anywhere in the folder path, it's not at a consistent depth.

 /jobs/job1/my_folder/subfolder/myfile.sc - Will NOT be deleted
 /jobs/job1/my_folder/cache/subfolder/myfile.sc - WILL be deleted

CodePudding user response:

In bash:

shopt -s globstar
printf %s\\n /**/cache/**/*.sc

If you are happy with the results, replace the printf %s\\n by rm.

CodePudding user response:

I believe find will solve your problem. First let's do a non-destructive test:

    find "/jobs/job1" -type f -regex '.*/cache/.*' -print

This will find all files:

  1. in the subfolder /jobs/job1
  2. is of a regular file type (i.e. not a directory)
  3. contains the word cache

If you are satisfied with the result, then, you can replace -print with -delete

    find "/jobs/job1" -type f -regex '.*/cache/.*' -delete
  • Related