Sometimes, my scripts get trapped in infinite loops. When the loop creates new files, things get messy.

I currently have this file name format:


where 4883 is a counter.

I need to delete all files, except the first 10 (i.e. counter in 0-9, inclusive). Currently, around 10k files are created before I can react and stop the script. SSD's are really fast.

It gets a bit harder by rm not accepting that many arguments: -bash: /bin/rm: Argument list too long

Oh, and I'm currently on a mac.

  • none of the answers addressed the point about the first ten. – Thomas Dickey Dec 29 '16 at 11:50
find . -name 'Task.??*.store.log' | xargs rm -f
| improve this answer | |
  • 1
    Is the -f necessary - or even a good idea? – mikeserv Jun 21 '15 at 21:52
  • 1
    It depends. If the files are read-only (unlikely) then yes (-f), but I agree that in this case it is probably not needed. However, in a non-interactive script I always use -f to avoid potential prompts. – meuh Jun 22 '15 at 5:28
  • A person copy/pasting the answer might not know where to put the -f flag, or that they need to add it, if the script does not work. – Filip Haglund Jun 22 '15 at 8:11

A POSIX one, can handle file which contain newline in filename:

find . -name 'Task.??*.store.log' -exec rm -f {} +
| improve this answer | |

With zsh:

rm Task.<10->.store.log 

To avoid the arguments list too long:

autoload zargs # best in ~/.zshrc 
zargs Task.<10->.store.log -- rm
| improve this answer | |

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.