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: Linux, remove spaces, rename, spaces, UNIX
June 15th, 2009 at 5:56 pm
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”.
August 11th, 2009 at 6:07 am
Nice. It is possible to string this all together in one line, of course.
June 22nd, 2010 at 9:28 pm
This does not work if you’re trying to remove whitespace from directories (and their subdirectories!) as well as all files. The logic in the code posted works so that directories are renamed recursively, and the paths to the files in subdirectories are not rewritten accordingly, so the deeply nested files are not renamed. You will have to rerun this code one additional time per each additional level of depth you have in your directory tree.
For one-shot solution in Perl, try here: http://www.perlmonks.org/?node_id=27739