How to delete files if a numerical part of their name is greater than a given number

filesfindrm

I've got files like this:

cap_20151023T122915_791033959.png
cap_20151023T122918_946392456.png
cap_20151023T122920_227637228.png
cap_20151023T122920_875467456.png

and I would like to use the find command to delete those greater than, for example, cap_20151023T122919*, which would result in the deletion of cap_20151023T122920_227637228.png and cap_20151023T122920_875467456.png.

Is there any way to do this, preferably with a single find command?

Best Answer

With zsh and <[x]-[y]> glob operator (matches numbers in the range x to y, inclusive; either of the numbers may be omitted to make the range open-ended) e.g.:

print -rl -- **/cap_20151023T<122920->_*

or, if you want to select only the file names in the 122920-999999 range:

print -rl -- **/cap_20151023T<122920-999999>_*

so with file names like:

tmp/cap_20151023T122915_791033959.png
tmp/cap_20151023T122915791_959.png
tmp/cap_20151023T122918_946392456.png
tmp/cap_20151023T122920_227637228.png
tmp/cap_20151023T1229205_875467456.png
tmp/cap_20151023T122920_875467456.png
tmp/cap_20151023T122980_227637228.png

the first one prints:

tmp/cap_20151023T122915791_959.png
tmp/cap_20151023T122920_227637228.png
tmp/cap_20151023T1229205_875467456.png
tmp/cap_20151023T122920_875467456.png
tmp/cap_20151023T122980_227637228.png

while the second one prints:

tmp/cap_20151023T122920_227637228.png
tmp/cap_20151023T122920_875467456.png
tmp/cap_20151023T122980_227637228.png

If you're happy with the result replace print -rl with rm -f

Related Question