Problem with the folder name in a for command

February 20, 2010 at 04:28:39
Specs: Windows 7

If you can see in the lines below I am trying to rename all the txt files to the foldername.

exampel: this is now:
c:/test/a b (2009)/test.txt

and it should be:
c:/test/a b (2009)/a b (2009).txt

hours of searching and this is the closest thing I've got, only I can't figur out what I've to type with the
FOLDERNAME.txt below:


@echo off

for /f "delims==" %%b in ('dir /b /s /on *.txt') do rename "%%~b" "FOLDERNAME.txt" & echo %%~b



I hope someone can help me because I am trying to fix this from yesterday.


See More: Problem with the folder name in a for command

Report •

February 20, 2010 at 04:40:54
First, I don't know why you're using "delims==".

Beyond that, after you rename the first one you'll get a name collision.

Because FOLDERNAME.txt already exists.

Helping others achieve escape felicity


Report •

February 20, 2010 at 04:59:03
hi, thanks for your reply

ok the "delims==" can go away I have found that on the net. but how Can I do this than?

Report •

February 20, 2010 at 05:33:26
I've take some liberties:

- assuming you mean "test.txt", not "*.txt" since then you will have the issue M2 mentions (only 1 file can be named in that directory)
- assuming all directories are in C:\test, no more directories levels deeper down

@echo off
setlocal enabledelayedexpansion

for /F %%f in ('dir C:\test\test.txt /s /b') do (
set dirname=%%~df%%~pf
set dirname=!dirname:C^:\test\=!
set dirname=!dirname:\=!
echo rename C:\test\!dirname!\test.txt !dirname!.txt

Report •

Related Solutions

February 20, 2010 at 06:18:24
I have found it this was what I was looking for:

@echo off
set thisdir="%cd%"
for /f "delims==" %%A in ('dir /b /s /ad') do if exist "%%A\*.txt" cd %%A & for %%B in (*.txt) do ren "%%~dpnxB" "%%~nA.txt"
cd %thisdir%


Thanks for your help!

Report •

February 20, 2010 at 06:26:58
It surprises me that that code works, but if you are happy, so are we !

Report •

Ask Question