Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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?

Comment on renaming files
Select or Download Code
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'
    or
    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:
      complete/La.Haine.1995.1080p.BluRay.DTS.x264-DON/lh-don.mkv
      complete/La.Haine.1995.1080p.BluRay.DTS.x264-DON/lh-don.nfo

      and would like to automagically rename it to this:

      complete/La.Haine.1995.1080p.BluRay.DTS.x264-DON/La.Haine.1995.1080p.BluRay.DTS.x264-DON.mkv
      complete/La.Haine.1995.1080p.BluRay.DTS.x264-DON/La.Haine.1995.1080p.BluRay.DTS.x264-DON.release

      All guidance is welcome :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://943851]
Approved by Eliya
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2015-07-30 10:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (271 votes), past polls