Tip: Remove spaces from filenames one-liner

There is often the case when you need to remove spaces from filenames - for instance when importing broken data feeds into Magento or osCommerce systems.

The following strips spaces and replaces them with nothing :-

find directoryname -name '* *' -type f | while read f; do mv "$f" "$(echo $f | sed s/" "/""/g)";  done

or alternatively replace them with underscores :-

find directoryname -name '* *' -type f | while read f; do mv "$f" "$(echo $f | sed s/" "/"_"/g)";  done

Or any other character/string combo you like, you can even be more clever moving them out into subdirectories with more sed magic but you get the idea.  The reason the read command is there is to get the spaces in found filenames which if you simply use a “for” loop, bash splits on the spaces.


Tags: developmentbashsedtipfilenames