Rename spaces to underscores

How to rename files with spaces to use the underscore character instead .. or any other web friendly character.

I’ve just been handed a zip full of files, and want to host them, but they’ve all got nice pretty spaces in the file names. I *know* we can do that, it’s 2012 after all, but for the sake of keeping it “web safe” and catering to any possible user I’m going to rename them.

Linux already has a nice tool for bulk renaming called rename. And using it for this is very straightforward:

rename <expression> <replacement> filename

So to turn space characters into underscores:

rename ' ' '_' *

But, the fun part is the rename that ships with Archlinux is NOT the rename that ships with Debian/Ubuntu – The Debian/Ubuntu one can take regular expressions in the form of rename ‘s/old/new/g’ * but the Archlinux one can not – The Archlinux one only looks for the first instance of the expression ‘ ‘. You could just run the command a bunch of times, but there is (always) a better way:

Install an AUR package for Rename Tool Project

yaourt -S rename

Which installs as renamexm as not to conflict with the installed on.

From there, we can go back to the original plan of removing those darn spaces with a simple bit of regex
[cc]
renamexm -s/\ /_/g *
[cc]

Codemonkey of Node.js, Django, PHP and all things HTML5 Solving tech challenges, one bit at a time.

Posted in bash Tagged with: , , , , ,
One comment on “Rename spaces to underscores
  1. Tom Ryder says:

    One good thing about

    rename

    is you can add

    -n

    to it for a “dry run”; it’ll show you what it was going to do without actually renaming anything.

Leave a Reply

Your email address will not be published. Required fields are marked *

*