Bash – replace spaces with underscore but replace multiple spaces with one

filenamesregular expressionrename

I use rename to underscore spaces in filenames, simply with:

rename "s/ /_/g" * 

but I encounter the problem that files downloaded from the internet often have multiple spaces. A nasty workaround I used (but works only for 3 spaces which in most cases is enough), but there has to be a more elegant approach than:

rename "s/   /_/g" *; rename "s/  /_/g" *; rename "s/ /_/g" *

Best Answer

The following worked for me:

rename 's/\s+/_/g' *

It will match one to unlimited instances of white space

Note this would also work for newlines and tabs, however based on your use case I think that would be preferable and not unwanted? But to match only space specifically you could do:

rename 's/ +/_/g' *
Related Question