21

I want to rename a lot of files on Mac OS X (10.7.2).. I don't have the perl package for the rename command.

My files have names like "T452-102456-0.png" and I want to delete the "-0" part. I know I can do this action by writing my own php-cli script, but I would like to know of an easier and faster solution.

Raphaël
  • 543
  • Isn't there logical contradiction between “a lot of pdf files” and “My files have names like "T452-102456-0.png"”? – manatwork Nov 07 '11 at 12:26
  • Oh... the type of files doesn't matter, but it's true ^^. I edit, thank you for your comment =) – Raphaël Nov 07 '11 at 13:14

4 Answers4

21

Bash or Ksh together with mv could solve it:

for f in *.png; do mv -n "$f" "${f/-0}"; done

In case the file name may have “0” after the first dash too and the “-0” is always in front of the dot, you may want to include that dot too in the expression:

for f in *.png; do mv -n "$f" "${f/-0./.}"; done

But as that renaming rule is simple, if you have rename from the util-linux package, that will do it too:

rename '-0.' '.' *.png
manatwork
  • 31,277
5

Simple method: Files in current directory only

With zsh:

autoload zmv
zmv '(*)-0(.png)' '$1$2'

With other shells:

for x in *-0.png; do mv -- "$x" "${x%-0.*}.png"; done


Enhanced method: Files in current directory and/or subdirectories

With zsh:

zmv '(**/)(*)-0(.png)' '$1$2$3'

With ksh93:

set -o globstar
for x in **/*-0.png; do mv -- "$x" "${x%-0.*}.png"; done

With bash ≥4, as above, but use shopt -s globstar instead of the set command.

With other shells:

find -name '*-0.png' -exec sh -c 'for x; do mv -- "$x" "${x%-0.*}.png"; done' _ {} +
syntaxerror
  • 2,246
  • another great reason to install zsh :)....zmv – danidee Aug 09 '16 at 14:21
  • zmv!!! cool! thanks. – sepideha Apr 20 '21 at 19:57
  • autoload zmv was helpful! And needed before it will work.

    Tip for others: add autoload zmv to your .zshrc file so you don't need to type it each time and learn about useful zmv options by running zmv with no parameters.

    – Ville May 23 '21 at 11:36
3

In Fish Shell on OSX:

for f in *.png; mv -n $f (basename $f -0.png).png; end

Fish Shell: https://fishshell.com/

0

If you have the mmv package:

mmv '*-0.png' '#1.png'

Like (recent versions of) rename, this will take reasonable care to avoid overwriting existing files.

Toby Speight
  • 8,678