Rename all files and folders (recursively) and replace all spaces with underscore _ character in Linux terminal.

So… Lets say You have folder Dupa in Your home folder and inside that folder – chaos… ;). Files with spaces in the file and folder names. You want to sanitize them and rename them so that they all contain _ instead of space? Do this:


cd ~/Dupa/

And then run:

find . -depth -name '* *'
| while IFS= read -r f ; do mv -i "$f" "$(dirname "$f")/$(basename "$f"|tr ' ' _)" ; done

This is a ONE command. Both lines.

Repeat until all the files and directories are renamed properly. I had to run this command several times before the chaos got whipped into a sensible shape.


If You want to check if there are any files or folders with spaces in the name left run:

find . | grep ' '





"Never meet Your heroes. Most of the time you'll only end up disappointed." White Polak Male Husband Employee Hetero Carnivorous Fugly Geek @$$hole with ADD Catholic “Some men just want to watch the world burn.”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.