Massrenaming with shell and python

28 October 2004   5 comments   Python, Linux

Mind That Age!

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

Powered by Fusion×

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