2012. február 20., hétfő

rename - a tool to rename files in batch

A long-forgotten Linux tool I found lately, called rename. It is a Perl script on Debian in the /usr/bin/ folder available as 'prename'. It is a very useful tool to rename files in a batch! Let's take an example. Suppose you've got a bunch of .sh extension files you want to rename to .bash in one step, of course.

$ ls -1 *.sh
atnev2.sh
atnev.sh
basecssfix.sh
child.sh
ekezefix.sh
$ rename 's/\.sh/\.bash/' *.sh
$ ls -1 *.bash
atnev2.bash
atnev.bash
basecssfix.bash
child.bash
ekezefix.bash


Brilliant! You can of course do it with writing a code shell script. I already had a Python solution as well, which I liked, but now it's good to know that rename is available as part of the main distribution. Look at the Python code below.


# File: rename.py
# Desc: renames files in a directory according to a given
#       global pattern
# Date: Tue, 23 Mar 2004 17:01:03 +0200
import glob, os

DIR1="./"
DIR2="./"

os.chdir(DIR1)
for file in glob.glob('*.jpg'):
        (base, extension) = os.path.splitext(file)
        os.rename(file, os.path.join(DIR2, base + '.png'))



The above code renames files with '.jpg' extension to '.png' in the current directory.  

Nincsenek megjegyzések: