Let's say there are 10 files in this current directory /home/usr. They are numbered 1-10. If I wanted to delete all the files except 9 and 10, how would I go about it?

I can select the bottom two files by doing

ls -l /home/usr/ | tail -2

However, how would I use this information to remove all BUT the last two? In other words, how would I remove 1-8?

I am going to clarify some things. I would like to remove based on the listing of ls -l and not specifically by the name of the files. As in those 1-10 files were examples. It should remove files regardless of the specific names and remove the bottom two of ls -l.

  • "I would like to remove based on the listing of ls -l and not specifically by the name of the files" Given that ls -l produces sorted output what do you perceive as the difference? – roaima Jan 17 '17 at 23:42

With zsh:

echo rm -f /home/usr/*(n[1,-3])

(remove echo when happy)

  • n to sort in numerical order (10 after 2)
  • [1,-3] to select only from the first to the third last.

(add the D glob qualifier if you also want to consider hidden files)

  • I tried this but it returned a syntax error: -bash: syntax error near unexpected token `(' I'm not too familiar with zsh. Would this be possible in .bash? – keyboard_solo Jan 17 '17 at 21:56
  • Actually I didn't understand what you meant at first. I realized how it needs to be formatted now. This makes sense. Thanks! To be specific, it was like this for me: echo rm -f /home/usr/[10, 9] – keyboard_solo Jan 17 '17 at 22:03
  • Wait... Sorry for all the confusion but wouldn't this essentially be "echo rm -f /home/usr/*9? and 10? How would I go about removing based on the bottom two on the list instead of specifically indicating the names on the files – keyboard_solo Jan 17 '17 at 22:15

Less beautiful non-zsh solution:

find . -name 'prefix*' | sort -V | head -n -2 | xargs echo rm --


  1. Assuming the files all share the same filename prefix prefix and have no newlines or other funny characters in their names.
  2. Your sort supports -V and it sorts correctly in your case (I tested it with files in the same simple prefix + number form and it works for me, generated using touch prefix{1..100} in bash BTW).
  3. Your head supports -n.

(The parameters should be supported on all current GNU/Linux distributions.)

Remove echo to unlock.


If your files are indeed named 1 to 10, you can use

rm {1,8}

Or a variation of this to indicate the range, such as foobar{1,8}.

Not the answer you're looking for? Browse other questions tagged or ask your own question.