Published

Single `mv` command to change all filenames in directory to lower case and replace spaces

This is the mv command I use to change all of the filenames in my current directory from mixed case to lowercase and replace spaces with underscores.

for file in *; do mv "$file" `echo $file | tr ' ' '_' | tr '[:upper:]' '[:lower:]'`  ; done

The ; semicolons indicate the end of each line of this command. To break it down:

  1. for file in * loops over all the files in the directory. You could change the * wildcard to something like *.jpg if you wanted to only target JPG files.
  2. do mv "$file" instructs the system to move each file in the loop to the location that immediately follows.
  3. `echo $file | tr ' ' '_' | tr '[:upper:]' '[:lower:]'` is the location we’re moving the file to. We use the tr “translate” command to replace spaces with underscores, and then again (separated by the | pipe character) to replace uppercase letters with lowercase letters. Then we echo that translated filename.
  4. done lets the system know that the loop is done.

I use this occasionally to prep files for use on the web when working on a static site, one that isn’t hooked it up to a CMS.