July 9, 2008
Batch-renaming files
I needed to number all image files in the current directory:
# current: 16090-04.png PySolFC_1.png h3teampysol_20080303103813.jpg pysol.gif pysol_420_2.gif 175928_large.jpeg Pysol.jpg linux-game-pysol03.png pysol460_big2.jpg # goal: pysolfc1.png pysolfc2.jpeg pysolfc3.gif pysolfc4.jpg pysolfc5.png pysolfc6.jpg pysolfc7.png pysolfc8.gif pysolfc9.jpg
Surprisingly easy in Common Lisp:
(loop for file in (directory "*") for i from 1 do (rename-file file (format nil "pysolfc~D" i)))
In plain sh programming, I would have had to extract directory component, basename and extension, modify the basename without the extension and put them all together again. And keep track of the index manually, too.
I suppose some shell guru might come up with a neat (and probably quite unreadable) solution, but I’d rather stick to Common Lisp.
I’m curious about other solutions, esp. in Shell (ZSH allowed!), Python, Ruby and less-known languages.
Comments(14)
Nice articel! Here’s one in bash, doesn’t look as neat as the lisp solution though ;-) (I hope I get the formatting right).
in python, it would probably look like this:
ZSH
Assuming the order of the destination files does not matter, this works in sh and the like:
@smoon, nice, after seeing your solution I am wondering what led me to use printf. Seems the first thing that came to my mind wasn’t the most obvious ;-).
Yea, if you’re looking for the ultimate in renaming, you should check out zmv.
I haven’t done anything in perl in a while, but your post got me motivated ;-). So here’s a solution in perl:
man rename
i have a file, temp.txt in folder c:/TMP/Arch
my script is in c:/script/script1.py
i want to rename the file temp.txt with the date and time, but my script rename the file and then move the file in c:/script/
can u tell me pls how to do ? i want the file with new name to remain in c:/TMP/Arch
my script
from time import time, localtime, strftime
time_tuple = localtime(time())
ddate = strftime(“%d.%m.%y-%H;%M;%S”, time_tuple)
ext = “.txt”
file = ‘c:/TMP/Arhiva/temp.txt’
(basename,ext) = os.path.splitext(file)
os.rename(file, ddate+ext)
Python:
or, a bit too clever perhaps:
Python’s penalized by explicit import of subsystems (the number of “built-ins” is relatively small), and less powerful formatting. But three lines are three lines… ;-)
Just a small issue with the python example, if run as a script it will rename itself.
How cute, it’s self-modifying code.
cool pieces of codes