Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

renaming files

by sueme (Novice)
on Dec 15, 2011 at 22:40 UTC ( #943851=perlquestion: print w/replies, xml ) Need Help??
sueme has asked for the wisdom of the Perl Monks concerning the following question:

I was writing a small script to rename some files which looks like this:
my @files = <*.mp3>; for my $file (@files) { my $file2; ($file2 = $file) =~ s/^(..).*/$1_my_guitar.mp3/; print $file . " " . $file2 . "\n"; }
Except that I intend to replace the print with an appropriate rename line. I was wondering if there was some kind of one liner that would accomplish the same thing or a neater way of doing it?

Replies are listed 'Best First'.
Re: renaming files
by Eliya (Vicar) on Dec 15, 2011 at 22:56 UTC

    If you want a one-liner, you could use the rename command (implemented in Perl) that is already installed on many systems.

Re: renaming files
by graff (Chancellor) on Dec 16, 2011 at 03:49 UTC
    ls *.mp3 | perl -lne '($n=$_)=~s/(..).*/$1_my_guitar.mp3/; rename $_, +$n'
    perl -e 'for (<*.mp3>){($n=$_)=~s/(..).*/$1_my_guitar.mp3/; rename $_, + $n}'
    (both are untested)
Re: renaming files
by TJPride (Pilgrim) on Dec 16, 2011 at 16:33 UTC
    use strict; use warnings; my ($dir, $file) = './'; ### Directory to process opendir(DIR, $dir) || die; while ($file = readdir(DIR)) { if ($file !~ /_my_guitar\.mp3/ && $file =~ /(.*)\.mp3/) { $_ = "$1_my_guitar.mp3"; `mv $dir$file $dir$_`; ### Or some other rename } }
      I've been playing with this snippet in order to rename some files inside folders. I have a folder with other folders inside which I would like to rename from somename.nfo to foldername.release.

      Folderstructure is like this:

      and would like to automagically rename it to this:


      All guidance is welcome :-)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://943851]
Approved by Eliya
and the fog begins to lift...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2017-09-23 18:33 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (273 votes). Check out past polls.