Remove all files with a prefix except the one of the largest size

You can use a combination of few utilities:

stat -c '%s %n' pre_* | sort -k1,1rn | tail -n +2 | cut -d' ' -f2 | xargs rm

Assuming GNU system and no unusual filenames.

  • stat gets the filesize and name separated by space for all pre_* files

  • sort sorts the file according to the file size, with highest sized one goes to top

  • tail -n +2 gets the rest of the files apart from the max sized one

  • cut -d' ' -f2 gets the file name only, and rm (xargs rm) does the removal


With zsh:

rm -f pre*(OL[2,-1])
  • OL: reverse order by size
  • [2,-1]: second to last only

The equivalent with bash and GNU utilities would be something like:

eval "files=($(LC_ALL=C ls --quoting-style=shell-always -dS ./pre*))"
rm -f "${files[@]:1}"

You may want to limit it to regular files, as the size for non-regular files has generally not much relevance:

rm -f pre*(.OL[2,-1])

(no direct bash+GNU equivalent). You may want to include symlinks to regular files and consider the size of the target of the symlinks:

rm -f pre*(-.OL[2,-1])

With ls, add the -L option to consider the size of the targets of symlinks.