Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

one liner to rename multiple files in a directory?

by VGR (Acolyte)
on Feb 15, 2010 at 20:55 UTC ( #823349=perlquestion: print w/ replies, xml ) Need Help??
VGR has asked for the wisdom of the Perl Monks concerning the following question:

Hi....
Do you know of a way to rename multiple files in a directory using a single line of code on the bash shell with perl? without using too many pipes :D
This is what the files in the current directory look like:
$ls [crap]Episode1.avi [crap]Episode2.avi ... .. .
I want it to look like:
$ls Episode1.avi Episode2.avi ... .. .
or
$ls Season1Episode1.avi Season1Episode2.avi .. .

Comment on one liner to rename multiple files in a directory?
Select or Download Code
Re: one liner to rename multiple files in a directory?
by goeb (Pilgrim) on Feb 15, 2010 at 21:16 UTC
    On a Debian system (maybe the same on others, I don't know): the perl package comes with a prename script (can usually be called as rename, without the leading p), it can rename files based on regular expressions. So it's Perl and it's only one line, something like rename 's/[crap]//' *.avi (replace crap, of course...).
Re: one liner to rename multiple files in a directory?
by ikegami (Pope) on Feb 15, 2010 at 21:17 UTC
    General pattern:
    ls -1 | perl -nle'$o=$_; s///; $n=$_; rename($o,$n)if!-e$n'
    As applied to your case:
    ls -1 *.avi | perl -nle'$o=$_; s/\[crap\]/Season1/; $n=$_; rename($o,$ +n)if!-e$n'

    I find if!-e$n essential. One a couple of occasions, I've managed to delete all but one file in a directory without it.

    There's a rename floating around script that takes regex patterns. That would be a better solution.

      great stuff Thanks Ikegami
Re: one liner to rename multiple files in a directory?
by toolic (Chancellor) on Feb 15, 2010 at 21:17 UTC
    I don't know how to do it with a Perl one-liner, but I have been using this script for years: ren-regexp

    It uses Perl regular expression syntax. This will work for your 1st example (to get rid of arbitrary leading crap):

    ren-regexp 's/^.*(Episode.*\.avi)/$1/' *Episode*.avi
Re: one liner to rename multiple files in a directory?
by eyepopslikeamosquito (Canon) on Feb 16, 2010 at 07:10 UTC

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (9)
As of 2014-11-24 00:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (134 votes), past polls