How to Remove Spaces from Filenames in Linux/UNIX

This command will rename all files that have spaces in their filenames, in the current directory and recursively in its subdirectories, so that in the new filenames all spaces are replaced with underscores (’_’ characters).

find . -name '* *' | while read file;
do
target=`echo "$file" | sed 's/ /_/g'`;
echo "Renaming '$file' to '$target'";
mv "$file" "$target";
done;

I tested the command with BASH, but it should work with most shells.

How it works

In case you’re interested in how the command works, here is a quick explanation.

1. We use the ‘find’ command to get a list of all files with spaces in their filenames, from the current directory:

find . -name '* *'

2. We ‘pipe’ the list of filenames to a while loop, that will individually process each filename, by reading it into an environmental variable called ‘file’.

while read file;
do
...
done;

3. Inside the while loop, we firstly work out what the new filename should be, by using ’sed’ to replace all spaces with underscores in the filename, then we print a message to the console using ‘echo’ and then finally, we rename the file using ‘mv’.

target=`echo "$file" | sed 's/ /_/g'`;
echo "Renaming '$file' to '$target'";
mv "$file" "$target";

Tags: , , , ,

  1. Justin

    Thanks for the script, funny how it took me almost an hour on google to find this, “replace spaces in filename for all files in directory”.

  2. MvE

    Nice. It is possible to string this all together in one line, of course.

Add a Comment