Changing Unix/Linux filenames to handle DOS conventions

Recently, I had a bunch of files with characters in their names that made them hard to handle under Windows. Although Unix has no problems with :, ? and others, DOS / Windows doesn’t handle them well. This made using them on my CIFS share a bit of a pain.

To rename them, I hacked up a quick Groovy script. It maps all “weird” characters to _, which is pretty much universal.

Note that this script doesn’t currently handle the case where two files map to the same name. If you have :foo and ?foo, they’ll both get mapped to _foo and you’ll lose one of them.

I called it dosname because it was late and I wasn’t feeling creative.

#!/usr/bin/groovy -
if(args.length == 0) {

dirName = args[0];
new File(dirName).eachFile() { file ->
    def matcher = (file.getName() =~ /[\?\:\"\\]/)
    def newName = matcher.replaceAll("_")
    File newFile = new File(dirName + "/" + newName.toString())
    println file.getName() + " -> " + newFile.getName()

def printArgs() {
	println("Usage: dosname [dirname]")
	println(" Note: I don't handle the case where two files map to the same filename yet!")

The interesting bit is in the line

def matcher = (file.getName() =~ /[\?\:\"\\]/)

That line defines the regular expression which contains a group of characters which will be replaced by _. Right now it’s [?:”\] (all quoted with \ because that’s what you have to do in regex).

Run it with “dosname directoryname“. There’s no way to reverse its effects, so try not to use it on useful directories like /etc/.

Also, I needed to install OpenJDK6 JDK (not just the runtime) in order to run Groovy on Ubuntu 9.04. Go figure.

Since I don’t know Groovy, I stole most of this code from here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: