Rename file with folder name

September 12, 2009 at 22:37:10
Specs: Windows Vista
Maybe it's my lack of knowledge of batch
syntax, but I need some help figuring this out:
I have a folder with a bunch of subdirectories
and this batch file. I want to rename each file
within those subdirectories to their respective
folder names, plus a sequential number if there
is more than one file in that subdirectory, and
then their proper file extension.

Thanks!


See More: Rename file with folder name

Report •


#1
September 13, 2009 at 00:00:35
It appears that I was able to get everything working except the
sequential numbers. I can't figure out why my counter variable
isn't counting! :(

@echo off

for /d %%x in (*.*) do (
call :Rename %%x
)
goto End

:Rename %*
set DirName=%*
set Count=1
echo.
echo Initial Count: %Count%
for %%f in ("%DirName%\*") do (
ren "%%f" "%DirName%_%Count%%%~xf"
set /a Count+=1
echo Incremented Count: %Count%
)
exit /b

:End
pause


Report •

#2
September 13, 2009 at 03:17:17
You probably need:

@echo off & setLocal EnableDELAYedExpansion

Then use !count!

[not tested]


=====================================
Helping others achieve escape felicity

M2


Report •

#3
September 13, 2009 at 04:09:54
@echo off & setLocal EnableDELAYedExpansion

for /f "tokens=* delims= " %%a in ('dir/s/b/ad') do (
  set N=
  pushd %%a
  set str=%%a
  call :sub1

for /f "tokens=* delims= " %%f in ('dir/b/a-d 2^>nul') do (
  set /a N+=1
  echo ren "%%f" "!str!_!N!%%~Xf"
)
)

goto :eof

:sub1 get last tok
  :loop
    for /f "tokens=1* delims=\" %%i in ("!str!") do (
      if "%%j" neq "" (
      set str=%%j
      goto :loop
      )
    )
goto :eof


=====================================
Helping others achieve escape felicity

M2


Report •

Related Solutions

#4
September 14, 2009 at 21:58:57
Okay, I was able to get it working except for one problem, If
there is an exclamation point (!) in the subdirectory or file
name, it will not work. This is my current code:

@echo off
setLocal EnableDELAYedExpansion

for /d %%x in (*.*) do (
call :Rename %%x
)
goto End

:Rename %*
set DirName=%*
set count=1
echo.
echo Initial count: %count%
for %%f in ("%DirName%\*") do (
if !count! equ 1 ren "%%f" "%DirName%%%~xf"
if !count! gtr 1 ren "%%f" "%DirName% (!count!)%%~xf" 
set /a count+=1
echo Incremented count: %count%
)
exit /b

:End


Report •

#5
September 14, 2009 at 23:12:06
Yep, some chars have 'special meaning'. I would just get rid if the ! in the filenames.

not elegant


=====================================
Helping others achieve escape felicity

M2


Report •


Ask Question