Gregg's MOTD

Tips & Tricks that I've Encountered Over the Years...

Removing Blank Spaces from a Group of File Names

September 21, 2023 — Gregg Szumowski

This set of commands iterate over each file in the current directory and will replace any blank spaces in a filename with an underscore (_).

First, we’ll create a set of sample files:

$ for i in {0..9}; do touch "file-${i} (number-${i}).txt"; done
$ ls
file-0\ (number-0).txt file-4\ (number-4).txt file-8\ (number-8).txt
file-1\ (number-1).txt file-5\ (number-5).txt file-9\ (number-9).txt
file-2\ (number-2).txt file-6\ (number-6).txt
file-3\ (number-3).txt file-7\ (number-7).txt

Now, we’ll execute the set of commands:

$ for f in *\ *; do mv "$f" "${f// /_}"; done

And now you can see that the blanks have been replaced.

$ ls
file-0_(number-0).txt file-4_(number-4).txt file-8_(number-8).txt
file-1_(number-1).txt file-5_(number-5).txt file-9_(number-9).txt
file-2_(number-2).txt file-6_(number-6).txt
file-3_(number-3).txt file-7_(number-7).txt

Tags: cli, bash, rename, motd