regular expressions and renaming files

David Lebel lebel at lebel.org
Wed Feb 18 12:25:27 EST 2004


Hi,

as a way to teach myself Perl, I started to convert my toolbox of
scripts from (mostly) Perl to Python.  One script I had in my toolbox
was used to rename files using a regular expression.  That script came
from Tom Christiansen (of Perl fame) and shows the great flexibility of
Perl doing regular expression operations.

Now, I don't know where to start doing the conversion.

Any insights?

#!/usr/bin/env perl

# Tom Christiansen <tchrist at convex.com>, in alt.sources, 90-12-08.
# Modified by François Pinard <pinard at iro.umontreal.ca>, 91-04-19.
#
# 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' *

$operation = shift;
for (@ARGV)
{
    $previous = $_;
    eval $operation;
    die $@ if $@;
    if ($previous ne $_)
    {
	if (-f $_)
	{
	    warn "$0: $_ already exists\n";
	}
	else
	{
	    rename($previous, $_)
		|| warn "$0: can't rename $previous to $_: $!\n";
	}
    }
}

-- 
// david lebel <lebel@{lebel.org,nobiaze.com,openbsd.org}> //
// http://www.lebel.org/           http://www.nobiaze.com/ //
// pgp: 3633 6999 D47E 73ED 099F  4341 08A4 8E48 EF56 61D1 //





More information about the Python-list mailing list