0

I just experimented a bit in linux and ended up getting very many files in one and the same folder. Now when I try to do

rm -f folder/*.png

I get

-bash: /bin/rm: Argument list too long

Is there some easy way to get past this?


Own work:

I suppose I could make an ugly script which loops through rm on the result of something like

ls /folder/ | head -100 | grep ".*\.png"

But really, there must be an easier Gnu way to do it?

mathreadler
  • 103
  • 1
  • 4
  • 7
    Related: [How many files can rm delete at once](http://unix.stackexchange.com/questions/209749/how-many-files-can-rm-delete-at-once) (look at the `find ... | xargs ...` answer) – Mark Plotnick Dec 07 '15 at 17:34

2 Answers2

2

I would do something like:

ls -1 | grep "\.png$" | xargs -L 50 rm -f 

This will match (and remove) only files ending with .png.

Kira
  • 4,727
  • 3
  • 17
  • 33
David King
  • 3,147
  • 8
  • 23
2

When you use rm -f folder/*.png or even simpler rm * then the shell (not rm) will expand the * to all relevant files. It will then call rm with all the filenames expanded. (e.g. if will do a `rm filename1 filename2 filename3 filename4 filename5 filename6 filename7 .... filename12345'

If that list is too long to pass you will get this error.

Solution: Split it in smaller chunks, or do not use the shell. E.g. find with --delete is a nice option.

  • find /path/to/file -name "*.PNG" -delete \;
  • find /path/to/file -name "*.PNG" -exec rm \; (runs rm once for each file)
  • find /path/to/file -name "*.PNG" -delete + (groups them into chunks just small enough to pass to rm)

The first option is the one I usually use. First tested with -print.

Hennes
  • 1,958
  • 14
  • 14