Another round of renaming scripts. This time I've tried to provide "functional" and "imperative" styles for Python and Perl. For this sort of problem I personally think of it as a problem of processing a list of names so I prefer the functional approach. If the end result were to be a list of some sort then I think the functional approaches win hands down. The presence of the rename "side effect" means that they're not pure but The Python imperative style is courtesy of Jarno Virtanen with a downgrade by me so it matches the functionality of the others.
As a Python script, functional style:
import glob
import os
map(lambda f: os.rename(f + '.txt', f + '.xml'),
[os.path.splitext(f)[0] for f in glob.glob('*.txt')])
As a Python script, imperative style:
import glob
import os
for filename in glob.glob('*.txt'):
base = os.path.splitext(filename)[0]
newname = '%s.%s' % (base, 'xml')
os.rename(base + '.txt', newname)
As a Perl script, functional style:
map(rename($_ . '.txt', $_ . '.xml'),
map(s/\.txt$//, glob('*.txt')))
As a Perl script, imperative style:
foreach $f (glob('*.txt')) {
$f =~ s/\.txt$//;
rename($f . '.txt', $f . '.xml');
}
Finally the shortest solution, provided by John Masson. As a Bash shell script from the command line:
for i in *.txt; do mv $i ${i%%.txt}.xml; done
Posted by Alex at October 29, 2002 01:52 PM