How can I rename a lot of files using a regex?

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

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' _ {} +

In Fish Shell on OSX:

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

Fish Shell: https://fishshell.com/

Tags:

Rename

Files