0

Possible Duplicate:
Batch renaming files

I want to rename files using their existing name as a base for the new one.

So if I can ls these files with

ls blue*+(.png)

I'd want to rename them something like

mv blue$(*)+(.png) $(1).png

except that doesn't work obviously. Is there syntax for these kind of variables in bash globbing or is there an easier way?

user1561108
  • 1,071

4 Answers4

3

The portable way to do this is

for f in blue*.png; do mv -- "$f" "${f#blue}"; done

All this requires is mv and works in not just bash but also any POSIX compatible shell which supports standard POSIX parameter expansion. No need for your system to have zsh or a particular version of rename installed.

jw013
  • 51,212
0

On Debian and derivatives (including Ubuntu), there's a rename command which can do what you want:

rename -n "s/\+\.png/.png/" blue*+.png

Remove the -n flag after testing to actualy apply the rename.

This rename command is a Perl script, not to be confused with the rename command from the util-linux suite. Other distributions may provide it as prename or rename.pl or not at all.

0

With bash:

zsh -c '
  autoload -U zmv
  zmv "blue(*).png" "\$1.png"'

;-). Or more seriously, you'll find that zsh's zmv is a very powerful tool for all sorts of renaming jobs. Contrary to scripts you may come up with, that tool (or any other tool dedicated for the task like mmv or rename) takes extra care not to clobber files and is more likely to be more robust in corner cases.

0

I don't see any easy way to do this in bash, but of course you can break the problem into several steps like cutting the prefix, remembering the extension and then replacing the several instances of the extension with single one.

for file in blue*+(.png); do tmp="${file#blue}"; extension="${file##*.}"; echo "$file" "${tmp/%+(.$extension)/}.$extension";done

if you are happy with the results, just type...

^echo^mv

and all the magic will happen. :)