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.
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* ;)
Thanks to Larry Wall this is child's play:
rename 's/_//g' *
Renames "_bad_girl.py" to "badgirl.py" but I didn't know of the rename command. I'll try to explore it some more.
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 ;)
# nulspaces.sh - 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`
mv $line $DN"/"$BN"| sh -s
$ cat /usr/bin/rename-without-spaces
rename "s/ /_/g" "$1"
$ cat /usr/bin/rename-lowercase
rename 'y/A-Z/a-z/' "$1"