Replace Space With Underscore in Filename

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

About Aldiantoro Nugroho

full-time dreamer.
This entry was posted in programming, python and tagged , , . Bookmark the permalink.
  • Do you have an outdoor space that you dream of entertaining in but it is lacking that certain something that makes it a place that you want to be? If so, there are some simple things that you can do to make the space your very own.
  • In Ubuntu, at least:
    rename 'y/ /_/' *

    rename is a perl script using perl regex. Therefore:

    "y/{0}/{1}/": Search list for all occurrences of {0} and substitute by {1}
    * : Feeds all files in current dir
  • marklee
    Well it is interesting, certification
    and what can I say to it but it doesn't agreed me cent by cent.
  • just_a_remark
    for f in *; do mv "$f" `echo $f | tr ' ' '_'`; done

    (not mine, taken from http://linuxconfig.wordpress.com/2008/01/04/rem...)

    BUT - I like python too much!
  • ZaQ
    *menunggu edisi november*
    *siul siul*
  • g33k! :D
blog comments powered by Disqus