Renaming files using wildcards

J

Jerry Blake

I have a folder with many files in it that I want to
rename with a common prefix. I want to add "c_" to the
front end of a filename and I want to do that all in one
fell swoop like this from a run cmd line:

Ren *.* c_*.*

It substitutes c_ for the first 2 characters of the
existing filename.

I've also tried ren *.* c_ & *.* and ren *.* + *.* and
they don't work. If this can be done from other than the
command line, that would be acceptable, as long as I
don't have to rename each file individually.
Any ideas?

Jerry
 
V

Vincent Fatica

Here's a one-liner that seems to work here in a folder with 1000 files
(no guarantees).

for /f %f in ('dir /b') do ren "%f" "c_%f"

That is: for each line in the output of the 'DIR /B" command (bare file
names), rename the file with the prefix "c_". I used double quotes to
avoid problems with file names containing spaces.

Try 'FOR /?' for more info on the FOR command

Using wildcards generally won't work. Wildcards cause windows to
enumerate the files in a directory. Using a command like the one below,
it is easy to get CMD.EXE into a loop wherein it keeps finding new files
(the newly renamed ones) and renames them again.

Don't do this: for %f in (*.*) do ren %f c_%f
 
G

Guest

Vince,

Thanks for your help. In my situation this all works
well except for situations where my file names contain
blank spaces. When I strip down the filenames of their
spaces, the rename works well. How can I rename the
files but keep the spaces?
I have reviewed the "for" command in Windows help, but
it's too complicated for me to understand. I'm guessing
that the FOR /f parameter parses the original file name
into the variable "f", stripping the name of it's
spaces. What actually happens is that, not only does it
strip the filename of it's spaces, it trunkates the file
name at the position the space occurs. In doing so,
rename command can't find the file name to rename when it
compares the original filename with the name in the
variable.

I have some programming skills and experience in MS
Foxpro so I have a feel for some of this thing, but I'm
lost when it comes to the Windows or DOS commands and
their parameters.

Jerry
 
V

Vincent Fatica

OK, I forgot that "FOR /F" parses each line into tokens, and your
getting only the first token. So do this:

for /f "tokens=*" %f in ('dir /b') do ren "%f" "c_%f"

That way, %f will contain all the tokens. That works here with files
whose names contain spaces.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top