0

Possible Duplicate:
Batch renaming files

I have some files that I wish to rename in a single command. The files are names thus. I want the E S Posthumus bit removed from the names and also the 01, 02 ...etc at the start of each file. How do I remove that?

Papul
  • 1

2 Answers2

4

It's possible to strip off filename prefixes using just bash. Note that the resulting filenames may collide e.g if you have two files with the same song title. Hence the -i switch:

for f in *.mp3; do mv -i "$f" "${f#*Posthumus - }"; done
2
rename 's/\d\d\s-\s[ .A-Za-z]+-\s//' *.mp3
01 - E.S. Posthumus - Ashielf Pi.mp3 renamed as Ashielf Pi.mp3
02 - E.S. Posthumus - Oraanu Pi.mp3 renamed as Oraanu Pi.mp3

Edit: If for some reason you don't have a version of rename installed which does the job, you can easily write the minimal version of the script yourself in Perl, and run that. This is from the Unix FAQ, and works with the regex I provided above:

    #!/usr/bin/perl
    #
    # rename script examples from lwall:
    #       rename 's/\.orig$//' *.orig
    #       rename 'y/A-Z/a-z/ unless /^Make/' *
    #       rename '$_ .= ".bad"' *.f
    #       rename 'print "$_: "; s/foo/bar/ if <stdin> =~ /^y/i' *

    $op = shift;
    for (@ARGV) {
        $was = $_;
        eval $op;
        die $@ if $@;
        rename($was,$_) unless $was eq $_;
    }
ire_and_curses
  • 12,232
  • 3
  • 38
  • 33
  • 2
    The problem with `rename` is multiple versions of it exist in the wild. Always double check and use your local version's documentation to avoid mishaps. – jw013 Sep 25 '12 at 17:46
  • @jw013 - really? That's interesting. How do they differ? My understanding was that `rename` is just a Perl script, accepting standard Perl regex. – ire_and_curses Sep 25 '12 at 17:47
  • I've never done a `rename` survey. Not all implementation are Perl scripts however. Just know that you should always check what syntax your `rename` supports before using it. – jw013 Sep 25 '12 at 17:59
  • 2
    @ire_and_curses - a good example is debian. `/usr/bin/rename` is a symlink that is managed by the alternatives system. Two different servers with the same OS/distro and version may not have the same `/usr/bin/rename`. – jordanm Sep 25 '12 at 18:08
  • @ire_and_curses Here is a manpage for the other rename: http://linux.die.net/man/1/rename - it comes from util-linux. – Random832 Sep 25 '12 at 18:30
  • Very interesting! I've updated my answer with a generic Perl script which will do the rename, if for some reason `/usr/bin/prename` isn't available. – ire_and_curses Sep 25 '12 at 18:37