How can I bulk replace the suffix for many files?

I have a lot of files like

  • NameSomthing-min.png
  • NameSomthing1-min.png
  • NameSomthing2-min.png

I would like to change all them to

  • NameSomthing.png
  • NameSomthing1.png
  • NameSomthing2.png

i.e., remove the characters -min from the name.  How would I do this?

marked as duplicate by Wildcard, garethTheRed, Jakuje, Scott, user79743 Feb 12 '16 at 7:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


This script may help:

for file in *-min.png; do
    echo mv "$file" "${file%-min.png}.png"

Remove the echo to actually execute the command.

  • This works, but I'm giving the benefit of the doubt, since he didn't quite specify if these are just .png files. So it seems the delimiter before the extension is the only thing we can count on? – polemon Feb 12 '16 at 6:56
  • @polemon I am playing it safe, being strict on what may get changed will make less of a problem for the user if the user is not careful (or has some basic knowledge of how CLI works). – user79743 Feb 12 '16 at 7:33

That depends on your shell. I use zsh, and this is the way I do it:

for i in *-min.*; do mv $i "${i%-*}.${i#*.}"; done

I advice checking out the manpage of your shell, and checking out a section similar to "parameter expansion" (as it is called in the zsh man page).

Similar solutions are available for bash and other shells as well (you did not specify which one you use).

Please note, that your particular solution always depends on the data and your goal. if you have the '-' as separator between the name and the suffix you want to get rid of, this is the way to go. If not, you might want to tailor the param expansion a little bit.

  • Be sure to echo first time otherwise u end up with a mess of u screw up. – wbg Feb 12 '16 at 6:45
  • Isn't this more bash-like solution? zsh has zmv to avoid the loop. – orion Feb 12 '16 at 7:45
  • @orion my zsh doesn't recognize zmv. Also, the more universal, the better, I'd say. Especially in this particular case. – polemon Feb 12 '16 at 7:46
  • You must load these extensions. autoload -U zmv in your .zshrc. True, portability is ok in scripts, but not when you need to do something quickly and easily in the command line. zsh is known precisely for little magic things that do complicated things automatically via builtin behaviour. It's for power users that don't mind investing time into learning and configuring their tool. The rest of us just stick with bash. – orion Feb 12 '16 at 7:51
  • @orion: it took me roughly 20 sec to come up with that one-liner. I found it much more difficult writing this answer, with all the markup and such. So sure, I'll put it in my .zshrc, but I'll keep using my one-liners. – polemon Feb 12 '16 at 7:56

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