One of the posts that keeps coming up in comments and email is the one I wrote about using the FOR command to rename files from the command line. I just got another request about it that intrigued me: how can you rename files that have spaces in them? It’s not just that you want to slap the file name in quotes; you want to actually extract part of the filename to reuse in the new filename. Hmmm.
After a bit of searching, and experimenting, I have it.
The Problem
The first thing I like to do is create a directory with a few empty files in it, named appropriately. In this case, I have:
Directory of F:\ToDo\test
Sun 10 Jun 07 11:19 <DIR> .
Sun 10 Jun 07 11:19 <DIR> ..
Sun 10 Jun 07 11:19 0 abc xxx 123.txt
Sun 10 Jun 07 11:19 0 abc xxx 456.txt
2 File(s) 0 bytes
The request is to rename the file “abc xxx 123.txt” to “123.txt”.
Testing Your Expression
Looking at it, it doesn’t seem too bad, but the way I’ve explained it in the original post won’t work. That’s because there, I have one delimiter, “.”, which will end up breaking the file name into two chunks: “abc xxx 123″ and “txt”. That doesn’t quite help. I need to break it into more chunks.
So, I did some searching and testing, and have come up with a way to break the file name into four chunks. One thing I do is run a non-destructive test, to see how my expression works. If you use the FOR command with a benign “do” section, like “echo”, then you can see how the filenames in your directory are broken up.
For instance, I’ve come up with the command:
for /f “tokens=1,2,3,4 delims=. ” %i in (’dir abc*.txt /b’) do echo %i-%j-%k-%l
Here, I want to break each file name into four parts, using the “.” and ” ” as delimiters. The stuff in the brackets is telling the for command what to read though; in this case, a bare directory listing, filtered on text files that begin with “abc”. I could have just done ‘dir *.* /b’ in here, but I didn’t want to mess up another other files. You can see my original post for more information about the FOR command.
At the end of the command, you can see my non-destructive test - simply echoing the four parts of the file name, with a hyphen in between in each. The results of this command are:
As you can see, this command breaks up the filenames perfectly.
The Solution
Now that I know that my tokens are being broken up properly, I can run the actually renaming command. In this case, the filename “abc xxx 123.txt” should be renamed to “abc.txt”. This command will do it for you:
for /f “tokens=1,2,3,4 delims=. ” %i in (’dir abc*.txt /b’) do rename “%i %j %k.%l” “%k.%l”
And here are the results:
And that’s all there is to it. It never ceases to amaze me how powerful using the FOR command is. If you play around with it, you can figure out all sorts of interesting things :)

