2006-01-17

Renaming files

Sometimes you acquire a collection of files that are stupidly named. I'm running into that at the moment with all my recent downloading of old DOS games and ROM images. Unlike Windows, Linux is case sensitive and sometimes it's easier to keep everything in lower (or upper) case.

Here's a quick perl hack that'll do this for every file in the current directory.

ls | perl -lne 'print "mv $_ ",lc($_)'

Warning: If you have a maliciously named file, like RM\ -RF *, you'll run into serious problems because you might actually execute this command.

Typing the above at the command line will give you a chance to look over the results, but it won't actually do anything to your files. If you like what you see, then do the same command again, but suffix it with | sh like this.

ls | perl -lne 'print "mv $_ ",lc($_)' | sh

Change lc to uc to convert everything to UPPER CASE.

Here's an example:

galoot@breezy:~/Images/temp$ ls                                              
NUBLU.GIF PERIODIC_TABLE.PNG UBUNTU_BUTTON_88X31.PNG YOUR_ASS_IS_GRASS.JPG
galoot@breezy:~/Images/temp$ ls | perl -lne 'print "mv $_ ",lc($_)'
mv NUBLU.GIF nublu.gif
mv PERIODIC_TABLE.PNG periodic_table.png
mv UBUNTU_BUTTON_88X31.PNG ubuntu_button_88x31.png
mv YOUR_ASS_IS_GRASS.JPG your_ass_is_grass.jpg
galoot@breezy:~/Images/temp$ ls | perl -lne 'print "mv $_ ",lc($_)' | sh
galoot@breezy:~/Images/temp$ ls
nublu.gif periodic_table.png ubuntu_button_88x31.png your_ass_is_grass.jpg
This little perl script isn't mine.

If you want to see what the command will do to a large directory before you commit to the changes, you can pipe it through "less" like this:

ls | perl -lne 'print "mv $_ ",lc($_)' | less

(Edit: This doesn't handle filenames with spaces in them. Can one of you hackers improve it?)

1 Comments:

At 4:39 AM, Blogger MeanMrMustard said...

There's probably an easier way of dealing with messy quoting on the perl command line, but this works for your 'files with spaces' issue and should be shell-agnostic within linux:

ls | perl -lne '$t=chr(0x27);print "mv $t$_$t $t", lc($_), $t'

 

Post a Comment

<< Home