Rename a counter file name in windows package
I want to change files from 1-example.txt to 200-example.txt (just change starting number) with below code:
@Echo off
setlocal ENABLEDELAYEDEXPANSION
SET /a counter=200
for /F %%i in ('dir /b/a-d *.txt') do (
for /F "usebackq tokens=1,* delims=-" %%c in ('%%i') do (
SET filename=%%i
:: Dunno how to fix
echo !filename:%%c=%counter%!
:: ren %%i %%newfilename
)
SET /a counter+=1
)
but it doesn't work, it shows 200 all the time. When I change the% counter! To! Counter! shows nothing . How do I fix the counter?
source to share
You can use this code:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "Counter=200"
for /F %%I in ('dir /A-D /B *-*.txt 2^>nul') do (
for /F "tokens=1* delims=-" %%A in ("%%~nxI") do set "NewFileName=!Counter!-%%B"
ren "%%~fI" "!NewFileName!"
set /A Counter+=1
)
endlocal
Just the filename with the file extension is treated as a string by the inner FOR loop because of the use %%~nxI
.
Whatever is left of the first hatch character is assigned to a loop variable A
, which is of no interest due to the old number.
All rights to the first dash are assigned to the loop variable B
, which is used to create a new filename with the current counter value. The new filename must be without a path.
To understand the commands used and how they work, open a Command Prompt window, run the following commands there, and carefully read all the help pages displayed for each command.
-
echo /?
-
endlocal /?
-
for /?
-
ren /?
-
set /?
-
setlocal /?
source to share