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.

2
  • Isn't there logical contradiction between “a lot of pdf files” and “My files have names like "T452-102456-0.png"”?
    – manatwork
    Nov 7, 2011 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, 2011 at 13:14

4 Answers 4

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
1
  • it works perfectly. Thank you very much =)
    – Raphaël
    Nov 7, 2011 at 13:13
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' _ {} +
3
  • another great reason to install zsh :)....zmv
    – danidee
    Aug 9, 2016 at 14:21
  • zmv!!! cool! thanks.
    – sepideha
    Apr 20, 2021 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, 2021 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/

1
  • 3
    And downvote for what reason? This is a valid answer to the question. Jul 12, 2017 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .