Friday, 7 August 2009

One Liner: Remove whitespace from filenames

Spaces in filenames can make all kinds of things break, it is good practice not to use them, but people do. So here is a good fix.

find . -type f -name "* *" -maxdepth 1| while read src; do mv "$src" `echo $src | tr " " "_"`; done

This script looks for all files in the current directory with a space in and moves them (which is how to rename things in unix) with spaces replaced by underscores. 

You could do the same with with perl too, which includes a check to stop overwriting of any existing files. 

find . -type f -maxdepth 1| perl -ne 'chomp; $o = $_; s/ /_/g; next if -e; rename $o, $_'; 

You could replace the find part with a simple ls but  this method makes it easy to change the -type f into a -type d to do the same thing on directories, or change the -maxdepth to work a a whole tree of directories. 

No comments:

Post a Comment