How to Remove Spaces or Other Characters From File Names on Mac

Both these commands work on most Linux and OSX/Mac machines.

Replace spaces with dashes in files in a directory

find . -depth -name "* *" -execdir rename 's/ /-/g' "{}" \;

Replace a range of characers using a regular expression.

This this will remove any characters not matching a-z (lower and upper case), numbers, and dashes and replace them with a dash. You can change the dash with any character you want by replacing the dash in the shell line below right before the ending g /-/g. It only does the replacements in the current directory. You can limit the files with the * file mask change. Like change to *.txt to only to .txt files.

rename 's/[^a-zA-Z0-9]-/-/g' *

Leave a Reply

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