Monday 23 July 2012

Removing spaces in filenames


Ever have a bunch of files with spaces in their names, and need to get rid of the spaces?

$ ls -1
My data.csv
Surfing USA - Beach boys.mp3
Who let the dogs out.mp3
Dear American Express.doc
thesis version2-oct2008 final revisions3 steves comments.tex

Some scripts and commands don't handle spaces nicely, without painful escaping of each and every space and each and every file name. You could use mv to rename each file individually, but I'd rather shove ghost peppers in my eyeballs, especially when there's an easy one-liner to do it for me.

The Easy Way

On the eight day, God created the rename command:
$ rename 's/ //g' ./*
The rename command takes a regular expression and a list of files, and renames each file according to the regular expression. See the man page for complete details, but the regular expression syntax is similar to Perl's. In our simple case, we search for any spaces ("/ /") and replacing them with nothing ("//").

The Hard Way

Another approach is to use bash to loop through each file, use sed to find spaces and replace them with nothing, and then use the mv command to finish it all up.
$ for file in *; do mv "$file" `echo $file | sed -e 's/  */_/g' -e 's/_-_/-/g' -e 's/[()]//g'`; done
Although much more involved and a pain to read, it achieves the same effect as the rename command. If the rename command is not available to you but bash is, then here's your ticket.

1 comment: