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 :)

Comments

4 Responses to “Replace Space With Underscore in Filename”

  1. Rinaldi on October 20th, 2008 11:37 am

    g33k! :D

  2. little brain on October 20th, 2008 1:31 pm

    no no no. geek is when you spend hours to find how to do in bash scripting since it’s, by logic, the right thing to do :P

  3. ZaQ on November 18th, 2008 3:07 pm

    *menunggu edisi november*
    *siul siul*

  4. just_a_remark on December 18th, 2008 2:46 am

    for f in *; do mv “$f” `echo $f | tr ‘ ‘ ‘_’`; done

    (not mine, taken from http://linuxconfig.wordpress.com/2008/01/04/remove-white-space-from-file-name-and-rename-it-with-bash-command/)

    BUT - I like python too much!

Leave a Reply