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
November 11th, 2011 at 6:35 pm
Thanks for the code and nice explanation — always appreciate the latter. Just starting to understand the power of sed.
November 18th, 2011 at 7:36 pm
Hello,
Thank you very much.
I wanted to remove () from file name..
and your script worked gr8
Keep up the godd work
best regards
December 5th, 2011 at 5:27 pm
Another way: rename “s/ *//g” *
December 5th, 2011 at 5:27 pm
PS: Doesn’t works recursively.
December 18th, 2011 at 6:39 am
Worked awesome, thanks! And yes, it worked recursively.
December 24th, 2011 at 12:14 am
There’s a tool for this => http://linux.die.net/man/1/detox
January 13th, 2012 at 8:27 pm
Lovely loop, Many thanks.