20

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.

  • Isn't there logical contradiction between “a lot of pdf files” and “My files have names like "T452-102456-0.png"”? – manatwork Nov 7 '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 7 '11 at 13:14
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
  • it works perfectly. Thank you very much =) – Raphaël Nov 7 '11 at 13:13
3

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' _ {} +
  • another great reason to install zsh :)....zmv – danidee Aug 9 '16 at 14:21
2

In Fish Shell on OSX:

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

Fish Shell: https://fishshell.com/

  • 2
    And downvote for what reason? This is a valid answer to the question. – jeffmcneill Jul 12 '17 at 5:51
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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