Massrenaming with shell and python

28 October 2004   5 comments   Python, Linux

Mind That Age!

This blog post is 14 years old! Most likely, its content is outdated. Especially if it's technical.

I had the problem today that several files in a directory started with an _ underscore character. (e.g. _red.gif). Instead of manually renaming each file used the power of shell and python to solve it. (and some help from my collegue of course). Fortunately none of the files had an underscore in the middle of the name so I could keep the command quiet simple:

$ find -iname '_*' \
| xargs python -c \
'import sys;print "\n".join(["mv %s %s"%(x, x.replace("_","")) for x in sys.argv[1:]])'\
| sh -s

Hardcore UNIX geeks might laugh at me for using a few characters too many or not using sed properly. Windows users might laugh at me for even trying and would prefer to do it manually or pay $40 for a shareware to do it. Well, it worked.


Jan Kokoska
Here is one Linux geek who didn't manage to figure out the crazy sed replace one-liner this time (because he was thinking about the generic case, i.e. not thinking).. other approaches are:

1) using tr,

for i in $(find -iname '_*') do; mv $i `echo $i | tr -d '_'`; done | sh -s

2) using simple sed,

for i in $(find -iname '_*') do; mv $i `echo $i | sed -e 's/_//'`; done | sh -s

3) OK, I didn't swallow my pride just yet.

find -iname '_*' | sed -e 's/\([^_]\+\)_\(.*\)/mv \1_\2 \1\2/' | sh -s

*cough* I thought Python was supposed to be efficient *cough* ;)
Shane Geiger
Thanks to Larry Wall this is child's play:

rename 's/_//g' *
Peter Bengtsson
Renames "" to "" but I didn't know of the rename command. I'll try to explore it some more.
john maclean
Wrote this script also to remove spaces from filenames. No need for cryptic sed. Thanks for the clues, but I couldn't understand your sed Jan ;)

#! /bin/bash
# - a script to remove spaces from files
# for safety we ask for file extension before we operate
# date : Sun Jan 9 02:09:55 GMT 2005
# clapham dot 99 at no spam please, sir tiscali, um, dot co, um, errr, uk

read -p “extension : ” EXT
find /home/jayeola/ -iname “* *"$EXT"” | while read line
BN=`basename “$line” |sed -e ’s/ /_/g’`
DN=`dirname “$line"`
mv “$line” “$DN"/"$BN"| sh -s
Shane Geiger
John, FYI:

$ cat /usr/bin/rename-without-spaces
rename "s/ /_/g" "$1"

$ cat /usr/bin/rename-lowercase
rename 'y/A-Z/a-z/' "$1"
Thank you for posting a comment

Your email will never ever be published

Related posts

Bush country 28 October 2004
Urwid - curses-based UI/widget library for Python 30 October 2004
Related by Text:
HTML Tree on Hacker News 18 May 2014
YouTube - Nigella's XXXmas 19 December 2008
How and why to use django-mongokit (aka. Django to MongoDB) 08 March 2010
How to track Google Analytics pageviews on non-web requests (with Python) 03 May 2016
hashin 0.7.0 and multiple packages 30 August 2016