Replace Space With Underscore in Filename

October 19th, 2008

This is merely my personal note. I was about to rename all my files under a directory. I need to replace the space with underscore character ('_'). My first thought was a simple bash script to do that. Apparently, it’s been very long time since my last bash coding session. I spent 15 minutes reading how to read all files and rename them. And I got nothing.

Luckily, I know python. Stupid me. Why didn’t I think it at first time. It was couple minutes of python and all the spaces were replaced by underscores. Thanks to python. All I did were

1
2
3
4
5
6
7
8
9
10
$ python
Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> files = os.listdir('./')
>>> for f in files:
...     os.rename(f, f.replace(' ', '_'))
... 
>>>

Or if you want to save in a script, you could you this

1
2
3
4
5
6
7
8
#!/usr/bin/python
 
import os
import sys
 
files = os.listdir(sys.argv[1])
for f in files:
    os.rename(f, f.replace(' ', '_'))

The script takes the directory path as the argument. You could modify the script to use regex to have a better rename rule :)