1

My folder structer looks like below:

folder1
        ---tmp
        ---sub1
folder2
        ---tmp
        ---sub2
folder3
        ---tmp
        ---sub3
folder4
        ---tmp
        ---sub4

I want to delete files which older than 30 days in all tmp folder.

list all tmp folder:

ls -d */tmp

delete all files which older than 30 days

find . -mtime +30 -type f -delete

Could i combine these 2 steps into one command line?

huynq9
  • 522
  • 8
  • 22
  • Possible duplicate of [find and delete file or folder older than x days](https://stackoverflow.com/q/31389483/608639), [Delete files older than 10 days using shell script in Unix](https://stackoverflow.com/q/13489398/608639), etc. – jww Jul 20 '18 at 13:39
  • @jww clearly the OP knows how to do this. What he was wondering about is how to restrict the file-selection to particular subdirectories with a well-known name. Are your suggestions related? Yes! Duplicates? Debatable. – kvantour Jul 20 '18 at 14:06

1 Answers1

3

What you can do is replace the . in your find with the actual directories you want to search in.

find */tmp -mtime +30 -type f -delete

If tmp can be several levels deeper then you might be interested in

find . -regex '.*/tmp/[^/]+' -mtime +30 -type f -delete

or similar to the first option, but by using the double-star globular expression (enabled with shopt -s globstar)

find **/tmp -mtime +30 -type f -delete

* Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirectories.

source: man bash

Note: you have to be careful though. Imagine that you have a directory folder1/tmp/foo/ then the above commands (with exception of the regex version) will select also files in folder1/tmp/foo and this might not be wanted. You might be interested in the extra option -maxdepth 1

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • 2
    @jww also I do not have a problem with downvoting. But I would appreciate it if you add some information. If it goes against the rules of how Stack Overflow works, point me to the rules and I will follow. If you have a problem with this answer because of a given logic which I overlooked. Then explain to me what the problem is. We are all here to learn and share. (ps I know [commenting is not needed with downvoting](https://meta.stackoverflow.com/questions/357436/), I'm just curious why) – kvantour Jul 20 '18 at 14:16