I do my best to be clearer this time!
I am writing a .bat file to compile single (for the moment) files of different supported languages (fortran, C, C++, etc..). Since for the moment it is for a single file, I made up with this architecture:
buildfile [-lang] filename
where if specified -lang can be either -cpp, -c, -for, etc.. If not specified, -lang will be assumed from file extension.
Now, I report the first piece of code (very beginning, so nothing comes before):
#echo off
:: check first input
if "%1"=="" goto :syntax
if "%1"=="-h" goto :syntax
if "%1"=="/h" goto :syntax
if "%1"=="/?" goto :syntax
if "%1"=="--help" goto :syntax
if "%1"=="/help" goto :syntax
echo %1 | findstr "^-" > inp.log
echo Not found >> inp.log
set "var="
for /f "tokens=* delims=" %%i in (inp.log) do (
echo Big I writes %%i
set "var=%%i"
set var
if "%var%"=="Not found" (
echo String not found
goto :end
if "%~x1"=="" goto :syntax
)
goto :end
)
After check if user asked for help, I want to check if character "-" is present (that means if -lang has been specified).
As first I had thought to redirect echo %1 | findstr "^-" > %avariable% and then if "%avariable%"=="" then character "-" was not specified, hence go to check for file extension with "%~x1" (DID NOT WORK).
Second I thought to place the findstr command in echoing %1 directly as the argument of the FOR /F loop, but if "-" was not present that exploded since the searching string was empty! (i.e. for /f "tokens=* delims=" %%i in (' echo %1 ^| findstr "^-" ') do ( )
So, lastly is what you see in the piece of code, writing output into a file and rereading it, but there's something not working properly.
I added the line "Not found" to avoid reading an empty file (since apparently was giving same error as option 2).
I see that when I do set var I see correctly "var=Not found", that would mean that var is correctly set.
But as soon as I get to the IF condition inside the FOR /F loop, that does not work.
I can imagine a much better and cleaner solution exists, so I am here to ask your help.
I would say same something not far from option 1 could be best, since you only do 2 operation (redirect and then IF condition), maybe I am missing some syntax to make it working.
Many thanks!
EDIT:
of course, if "-" character is found, then I do a simple spell check to assume language (via many IF statements)
PS: all goto are there as debug.
EDIT EDIT:
it seems I solved the problem with removing var variable, using directly %%i one:
#echo off
:: check first input
if "%1"=="" goto :syntax
if "%1"=="-h" goto :syntax
if "%1"=="/h" goto :syntax
if "%1"=="/?" goto :syntax
if "%1"=="--help" goto :syntax
if "%1"=="/help" goto :syntax
echo %1 | findstr "^-" > inp.log
echo Not found>> inp.log
set "var="
for /f "tokens=* delims=" %%i in (inp.log) do (
echo Big I writes %%i
if "%%i"=="Not found" (
echo String not found
echo %~x1
if "%~x1"=="" goto :syntax
) else (
echo String found!
if "%1"=="-cpp" shift & goto :cppfile
if "%1"=="-c" shift & goto :cppfile
if "%1"=="-for" shift & goto :fortranfile
:: if one comes here, format not supported.
goto :syntax
)
)
Related
I'm coding a batch file that should search two folder paths for multiple file extensions and list them in a text file. Currently I'm trying to use a FOR loop with a list of file extensions (*.doc, *.docx, etc). I believe the file is erroring out because of the "*" character but I don't know how to correct this.
I've tried to straight list them: FOR %%G IN (*.one,*.mht,*.onepkg). I've tried quote marks: FOR %%G IN ("*.one","*.mht","*.onepkg"). I've tried carets: FOR %%G IN (^^*.one,^^*.mht,^^*.onepkg).
Here's my code:
set outputfilepath=d:\output.txt
FOR %%G IN ("*.one","*.mht","*.onepkg") DO (
echo Searching for %%G files
dir "C:\%%G" /s /b >> "%outputfilepath%"
Rem Add 2 blank lines between next search
echo. >> "%outputfilepath%"
echo. >> "%outputfilepath%" )
Nothing gets output to my text file.
Any help is appreciated.
#ECHO Off
SETLOCAL
set "outputfilepath=u:\output.txt"
(
FOR %%G IN (one,mht,onepkg) DO (
echo Searching for %%G files>con
dir ".\*.%%G" /s /b |FINDSTR /i /e /L ".%%G"
Rem Add 2 blank lines between next search
echo.
echo.
)
)> "%outputfilepath%"
GOTO :EOF
Please note that I've changed drivenames to suit my system.
simply for meta in extensionlist then add the * in the dir command. Filter the dir output using findstr to ensure that only names matching /e at the end /L the literal ".%%G" are shown.
Also by enclosing the enitre for command in parentheses, you can send all stdout text (which would normally appear on the console) to the file. > naturally means create-file-anew. >> to append if that's your preference.
The >con appended to the Searching... echo overrides the redirection and specifically sends the text from that echo to the console.
I really like the existing suggestions but this is a different approach. I find that this style reads more like code.
This may seem very complicated but...
This technique can be used to loop over parameters for ANYTHING to include ones passed via the command line.
The logic of looping through passed parameters is isolated to its own function (enumerate_search_types).
The logic of what you are going to do with each parameter is isolated to its own function (search_for_search_type).
This might make it easier for some, too complicated for others.
#echo off
:: The parameters we are working with...
set outputfilepath=d:\output.txt
set starting_path=c:\
set search_types="*.one" "*.mht" "*.onepkg"
pushd "%starting_path%"
call :enumerate_search_types %search_types%
popd
goto :EOF
:: ---------------------------------------------------------------
:enumerate_search_types
set "current_param=%~1"
if "%current_param%"=="" goto :EOF
call :search_for_search_type "%current_param%"
shift /1
goto :enumerate_search_types
:: ---------------------------------------------------------------
:search_for_search_type
set "current_search_type=%1"
set "had_output=false"
echo Searching for %current_search_type% files
for /f "delims=" %%f in ('dir /s /b %current_search_type% 2^>NUL') do set had_output=true&& echo %%f >> "%outputfilepath%"
:: If the dir command didn't produce anything, don't add the blank lines
if "false"=="%had_output%" goto :EOF
echo. >> "%outputfilepath%"
echo. >> "%outputfilepath%"
goto :EOF
Short answer if you refer to only the file extension.
In order to use different extension in a for loop:
FOR %%G IN (one,mht,onepkg) do [command]
I want to know how to use Findstr command to find a text in a file and make it a variable here what i tried :
#echo off
for /F "delims=" %%a in ('findstr /I /m "100" Config.dat') do set "Variable=%%a"
cls
if %errorlevel% == 0 (
goto found
) else (
goto nope
)
:found
cls
echo founded ! %Variable%
pause
exit
:nope
cls
echo not found!
pause
exit
Ok i explain : In the 2nd line the number "100" is what i want to find and the "Config.dat" is the file that have in it the number 100 and some other numbers and the "Variable" in there is the name of the variable that i want to store in it 100.
The problem is when it founded number 100 it goes to the function "found" and displays "Founded! 100" but when it not founded it also goes to "found" function and only display founded! without 100. So why when it didn't founded it it goes to "found" i need it to go to "nope".
So i hope you guys explain to me if i did something wrong and thanks!
This is because for /F calls command in a standalone cmd.exe process and does not return the error level into context of the caller:
#echo off
rem drop last error level
type nul>nul
for /F "usebackq delims=" %%a in (`cmd.exe /C #exit /b 123`) do rem
echo ERRORLEVEL=%ERRORLEVEL%
-
ERRORLEVEL=0
If you want just load config values into environment variables, then there is no need to search anything. Just create standalone configuration file for that.
config.vars
# loads by cmd.exe script
aaa=111
"bbb=111 222"
/A ccc=1+1
"ddd=%bbb% & 333"
load_config.bat
#echo off
for /F "usebackq eol=# tokens=* delims=" %%i in ("config.vars") do (
call set %%i
)
I'm trying to make a batch file which checks if the user input does exist in xy.txt well thats easy
but now if the user input is "hello world" i want to check each word individually.
i tried that..
#setlocal enableextensions enabledelayedexpansion
#echo off
:start
set /p word=" "
for /F "tokens=* delims= " %%A in ("%word%") do set A=%%A & set B=%%B
if %A%=="" goto Anovalue
if not %A%=="" goto checkforA
:Anovalue
echo first word has no value
pause
if %B%=="" goto Bnovalue
if not %A%=="" goto checkforB
:Bnovalue
echo second word has no value
pause
goto start
:checkforA
findstr /c:"%A%" xy.txt > NUL
if ERRORLEVEL 1 goto notexistA
if ERRORLEVEL 2 goto existA
:checkforB
findstr /c:"%B%" xy.txt > NUL
if ERRORLEVEL 1 goto notexistB
if ERRORLEVEL 2 goto existB
:existA
echo first word does exist in xy.txt
pause
goto checkforB
:existB
echo second word does exist in xy.txt
pause
goto start
:notexistA
echo first word does not exist in xy.txt
pause
(echo %A%) >>xy.txt
goto checkforB
:notexistB
echo second word does not exist in xy.txt
pause
(echo %B%) >>xy.txt
goto start\
Couldn't I do that in a more easier and smarter way?
There are a lot of ways to do what you are asking to do, many of which use a lot less code. For instance, given the following file xy.txt:
this is a test of the
system to see if it
will work the way
that i want it to
work today
This batchfile (check.bat):
#echo off
setlocal ENABLEDELAYEDEXPANSION
set words=%1
set words=!words:"=!
for %%i in (!words!) do findstr /I /C:"%%i" xy.txt > NUL && echo Found - %%i || echo Not Found - %%i
endlocal
Well return the following:
c:\>check "is test smart"
Found - is
Found - test
Not Found - smart
However, words within a word will also return true. For instance, check "day" will find day, even though it is not a separate word because it is part of today. Handling that situation would be a little more tricky. To do that, you need to encapsulate the search words with some character, and then replace all the spaces in xy.txt with the same encapsulation character. For instance, if we use a ., replace all spaces in xy.txt whwith the ., and then search for .word., we will find only whole words that match.
#echo off
setlocal ENABLEDELAYEDEXPANSION
set words=%1
set words=!words:"=!
set words=.!words: =. .!.
for /f "tokens=* delims=" %%i in (xy.txt) do (
set line=%%i
set line=.!line: =.!.
echo !line!>>xy.txt.tmp
)
for %%i in (!words!) do (
set word=%%i
set word=!word:.=!
findstr /I /C:"%%i" xy.txt.tmp > NUL && echo Found - !word! || echo Not Found - !word!
)
del xy.txt.tmp
endlocal
I chose to create an intermediary file xy.txt.tmp to house the edited file where the spaces are replaced with .. Then we can execute the following command and get the displayed results:
c:\>check "this is a test of the stem today that will work each day"
Found - this
Found - is
Found - a
Found - test
Found - of
Found - the
Not Found - stem
Found - today
Found - that
Found - will
Found - work
Not Found - each
Not Found - day
It correctly finds words at the beginning of the line, end of the line and anywhere in between. The only downside is the intermediate file that it creates and then deletes. Doing it without an intermediate file would be a bit more complex...
Task in CMD.
1) How can I compare if string is in string? I checked manual here for "Boolean Test "does string exist ?"" But I can't understand the example or it does not work for me. This piece of code, it is just a try. I try to make a string compare of filter some sting if there is a tag <a> in a line.
FOR /f "tokens=* delims= usebackq" %%c in ("%source%") DO (
echo %%c
IF %%c == "<a" (pause)
)
So while I read a file, it should be paused if there is a link on a line.
2) I have one more ask. I would need to filter the line if there is a specific file in the link, and get content of the link. My original idea was to try to use findstr with regex, but it seems not to use sub-patterns. And next problem would be how to get the result to variable.
set "pdf=0_1_en.pdf"
type "%source%" | grep "%pdf%" | findstr /r /c:"%pdf%.*>(.*).*</a>"
So in summary, I want to go through file and if there is a link like this: REPAIRED: *
<b>GEN 0.1 Preface</b>
I forgot to style this as a code, so the inside of code was not displayed. Sorry.
Warnning: we don't know the path, only the basic filename.
Get the title GEN 0.1 Preface. But you should know, that there are also similar links with same link, which contain image, not a text inside a tag.
Code according Aacini to be changed a little bit:
#echo off
setlocal EnableDelayedExpansion
set "source=GEN 0 GENERAL.html"
set "pdf=0_1_en.pdf"
echo In file:%source%
echo Look for anchor:%pdf%
rem Process each line in %source% file:
for /F "usebackq delims=" %%c in ("%source%") do (
set "line=%%c"
rem Test if the line contain a "tag" that start with "<a" string:
set "tag=!line:*<a=!"
if not "!tag!" == "!line!" (
rem Take the string in tag that end in ">"
for /F "delims=^>" %%a in ("!tag!") do set "link=%%a"
echo Link found: !link!
if "!link!" == "GEN 0.1 Preface" echo Seeked link found
)
)
pause
Still not finished
Although your question is extensive it does not provide to much details, so I assumed several points because I don't know too much about .PDF files, tags, etc.
#echo off
setlocal EnableDelayedExpansion
set "source=GEN 0 GENERAL.html"
set "pdf=0_1_en.pdf"
echo In file: "%source%"
echo Look for anchor: "%pdf%"
rem Process each line in %source% file:
for /F "usebackq delims=" %%c in ("%source%") do (
set "line=%%c"
rem Test if the line contain "<a>" tag:
set "tag=!line:*<a>=!"
if not "!tag!" == "!line!" (
rem Test if "<a>" tag contain the anchor pdf file:
if not "!tag:%pdf%=!" == "!tag!" (
rem Get the value of "<b>" sub-tag
set "tag=!tag:<b>=$!"
set "tag=!tag:</b>=$!"
for /F "tokens=2 delims=$" %%b in ("!tag!") do set title=%%b
echo Title found: "!title!"
)
)
)
pause
Any missing point can be added or fixed, if you give me precise details about them.
EDIT: I fixed the program above after last indications from the OP. I used $ character to get the Title value; if this character may exist in original Tag, it must be changed by another unused one.
I tested this program with this "GEN 0 GENERAL.html" example file:
Line one
<a>href="/Dokumenter/EK_GEN_0_X_en.pdf" class="uline"><b>GEN 0.X Preface</b></a>
Line three
<a>href="/Dokumenter/EK_GEN_0_1_en.pdf" class="uline"><b>GEN 0.1 Preface</b></a>
Line five
and get this result:
In file: "GEN 0 GENERAL.html"
Look for anchor: "0_1_en.pdf"
Title found: "GEN 0.1 Preface"
EDIT: New faster method added
There is a simpler and faster method to solve this problem that, however, may fail if a line contains more than one tag:
#echo off
setlocal EnableDelayedExpansion
set "source=GEN 0 GENERAL.html"
set "pdf=0_1_en.pdf"
echo In file: "%source%"
echo Look for anchor: "%pdf%"
for /F "delims=" %%c in ('findstr /C:"<a>" "%source%" ^| findstr /C:"%pdf%"') do (
set "tag=%%c"
rem Get the value of "<b>" sub-tag
set "tag=!tag:<b>=$!"
set "tag=!tag:</b>=$!"
for /F "tokens=2 delims=$" %%b in ("!tag!") do set title=%%b
echo Title found: "!title!"
)
pause
First, one important question: does this really have to be implemented via a CMD script? Would you be able to go with VBScript, PowerShell, C#, or some other scripting/programming language? CMD is a notoriously painful scripting environment.
Secondly, I'm not sure if this answers your question--it's a bit unclear--but here's a quick trick you can use to see in CMD to see if a given string contains another substring:
setlocal enableextensions enabledelayedexpansion
set PATTERN=somepattern
for /f "delims=" %%f in (somefile.txt) do (
set CURRENT_LINE=%%f
if "!CURRENT_LINE:%PATTERN%=!" neq "!TEMP!" (
echo Found pattern in line: %%f
)
)
The idea is that you try to perform string replacement and see if anything was changed. This is certainly a hack, and it would be preferable if you could instead use a tool like findstr or grep, but if you're limited in your options, something like the above should work.
NOTE: I haven't actually run the above script excerpt, so let me know if you have any difficulty with it.
I have modified the way to do it. I realized that it is better to find name of pdf document first. This is my almost completed solution, but I ask you if you could help me with the last point. The last replacing statement does not work because I need to remove closing tag b. Just to get the title.
#echo off
setlocal EnableDelayedExpansion
set "source=GEN 0 GENERAL.html"
set "pdf=0_1_en.pdf"
echo In file:%source%
echo Look for anchor:%pdf%
rem Process each line in %source% file:
for /F "usebackq delims=" %%c in ("%source%") do (
set "line=%%c"
REM Test if the line contains pdf file I look for:
SET "pdfline=!line:%pdf%=!"
if not "!pdfline!" == "!line!" (
cls
echo Line: !line!
REM Test if the pdfline contains tag b
SET "tagline=!pdfline:*><b>=!"
if not "!tagline!" == "!pdfline!" (
cls
echo ACTUAL LINE: !tagline!
REM Remove closing tag b
SET "title=!tagline:</b*=!"
echo TITLE: !title!
pause
)
)
)
pause
BTW:
The html page I work with is here.
So I ask you to help complete/repair line SET "title=!tagline:</b*=!"
i am writing a batch script monotonic file renamer. basically, it makes the titles of all the files 1 2 3 4 .... and so on. i have since expanded it to be able to handle files of different types (txt, doc, flv, etc) but not everything is working out.
my main concern is i have broken the delayed expansion calls i was making before. now using !var1! is never expanded, or never recognized as a variable.
here is a verbosely commented version of my script
::a monotonic file renamer
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET tempfile=temp.txt
SET exttemp=exttemp.txt
if [%1] == [] goto usage
::make sure your dont overwrite something useful
if EXIST %tempfile% (
ECHO Temp file already exists, are you sure you want to delete?
del /P %tempfile%
)
if EXIST %exttemp% (
ECHO EXT Temp file already exists, are you sure you want to delete?
del /P %exttemp%
)
::initialize
SET /a counter=0
SET type=
SET /a ender=%1
::write filenames to tempfile
DIR /B /ON > %tempfile%
::read lines one by one
for /f "usebackq delims=" %%a in (%tempfile%) do (
REM make sure we do not rename any of the working files
if NOT "%%a"=="renamer.bat" (
if NOT "%%a"=="temp.txt" (
if NOT "%%a"=="exttostr.bat" (
SET /a counter+=1
REM get file extension
exttostr %%a > %exttemp%
SET /P type= < %exttemp%
REM housekeeping
del /F %exttemp%
REM rename
ren %%a !counter!.!type!
ECHO Renamed "%%a" to "!counter!.!type!"
)))
REM exit when we have run enough
if "!counter!"=="!ender!" goto exit
)
goto exit
:usage
echo Usage: renamer NUMFILES
:exit
::final housekeeping
DEL temp.txt
the idea is i drop my two files, renamer.bat(this file) and exttostr.bat(helper to get the file extension) into the folder and run it, it will rename files sorted alphabetically from 1 to how ever many files i specify.
when i run the code, it never uses the variables marked for delayed expansion appropriately, always leaving them as "!varname!", so it renames the first file "!counter!.!type!" and throws errors for the rest because there is already a file in the directory with that name.
this brings me to a secondary issue. sorting the dir list alphabetically results in a poor handling of numbered files. for example the list:
"1 7 15 75 120"
is sorted:
"1 120 15 7 75"
i have not been able to find a way around this yet, only that it is indeed the intended result of the dir sort. the only workaround i have is padding numbers with enough zeroes in the front.
thanks in advance for any insight!
everything is sorted but the second problem. i think i have not spoken well. i have this issue when i take IN the directory file names, not when writing out. so they already need to be padded. i has hoping there was some other way to read the directory and have it be sorted appropriately.
the most promising thing i have found is here: http://www.dostips.com/DtCodeBatchFiles.php#Batch.SortTextWithNumbers
#ECHO OFF
if "%~1"=="/?" (
echo.Sorts text by handling first number in line as number not text
echo.
echo.%~n0 [n]
echo.
echo. n Specifies the character number, n, to
echo. begin each comparison. 3 indicates that
echo. each comparison should begin at the 3rd
echo. character in each line. Lines with fewer
echo. than n characters collate before other lines.
echo. By default comparisons start at the first
echo. character in each line.
echo.
echo.Description:
echo. 'abc10def3' is bigger than 'abc9def4' because
echo. first number in first string is 10
echo. first number in second string is 9
echo. whereas normal text compare returns
echo. 'abc10def3' smaller than 'abc9def4'
echo.
echo.Example:
echo. To sort a directory pipe the output of the dir
echo. command into %~n0 like this:
echo. dir /b^|%~n0
echo.
echo.Source: http://www.dostips.com
goto:EOF
)
if "%~1" NEQ "~" (
for /f "tokens=1,* delims=," %%a in ('"%~f0 ~ %*|sort"') do echo.%%b
goto:EOF
)
SETLOCAL ENABLEDELAYEDEXPANSION
set /a n=%~2+0
for /f "tokens=1,* delims=]" %%A in ('"find /n /v """') do (
set f=,%%B
(
set f0=!f:~0,%n%!
set f0=!f0:~1!
rem call call set f=,%%%%f:*%%f0%%=%%%%
set f=,!f:~%n%!
)
for /f "delims=1234567890" %%b in ("!f!") do (
set f1=%%b
set f1=!f1:~1!
call set f=0%%f:*%%b=%%
)
for /f "delims=abcdefghijklmnopqrstuwwxyzABCDEFGHIJKLMNOPQRSTUWWXYZ~`##$*_-+=:;',.?/\ " %%b in ("!f!") do (
set f2=00000000000000000000%%b
set f2=!f2:~-20!
call set f=%%f:*%%b=%%
)
echo.!f1!!f2!!f!,%%B
rem echo.-!f0!*!f1!*!f2!*!f!*%%a>&2
)
this code can sort the filenames with one number in them (i.e. video100.mov is fine, video100video10.mov would break it)
the issue i have is i think adding a call to this helper fn will break it again, so i will be trying to include this in my modified renamer.bat now. any help is appreciated.
Probably the batch for extracting the extension reset the local environment.
But, you don't need it. You may extract the extension with the ~x option. Something similar to this ....
:monotonicrename
set /a counter = 0
for %%a in (%1\*.*) do (
if exist %%~fa (
set /a counter += 1
echo ren %%~fa !counter!%%~xa
)
)
goto :eof
to include leading zeroes in the counter, so that the directory sorts correctly, replace the previous rename command with three lines
set zcounter=0000!counter!
set zcounter=!zcounter:~-4!
echo ren %%~fa !counter!%%~xa
So putting all pieces together, add the monotonicrename function you just created in the batch file that can be as simpler as...
#echo off
setlocal enabledelayedexpansion
call :monotonicrename %1
goto :eof
:monotonicrename
set /a counter = 0
for %%a in (%1\*.*) do (
if exist %%~fa (
set /a counter += 1
set zcounter=0000!counter!
set zcounter=!zcounter:~-4!
echo ren %%~fa !zcounter!%%~xa
)
)
goto :eof
I didn't experience any issues with delayed expansion, everything worked fine for me (except, of course, for the fact that I didn't have the exttostr.bat helper script.)
Anyway, there are several things that could be improved about your script:
You don't need to store the result of DIR into a file to read it afterwards. You can read the output directly in the FOR loop.
You don't need the helper batch script. The extension can be extracted from %%a by using the ~x modifier with the loop variable: %%~xa. You can read more about modifiers by issuing HELP FOR from the command prompt.
The renamer batch file's own name can be referenced in the script as %0. You can apply the ~n modifier where you only need to use the name without the extension. The combined modifier of ~nx will give you the name with the extension.
So, here's how your script might look like with the above issues addressed:
::a monotonic file renamer
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
IF [%1] == [] GOTO usage
::initialize
SET /A counter=0
SET type=
SET /A ender=%1
::read lines one by one
FOR /F "usebackq delims=" %%a IN (`DIR /B /ON`) DO (
REM make sure we do not rename any of the working files
IF NOT "%%~a"=="%~nx0" (
SET /A counter+=1
RENAME "%%~a" "!counter!%%~xa"
ECHO Renamed "%%~a" to "!counter!%%~xa"
)
REM exit when we have run enough
IF "!counter!"=="!ender!" GOTO :EOF
)
GOTO :EOF
:usage
ECHO Usage: %~n0 NUMFILES
As for your secondary issue, it can be easily resolved like this:
Use something like 100000 as counter's initial value. (Use however many 0s you like, but possibly no more than nine.) Add the same value to ender as well.
When renaming files, instead of !counter! use the expression that removes the first character (the 1): !counter:~1! (in fact, this is not about removal, but about extracting a substring starting from the offset of 1, learn more about it with the HELP SET command).
Here's the modified version of the above script:
::a monotonic file renamer
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
IF [%1] == [] GOTO usage
::initialize
SET /A counter=1000
SET type=
SET /A ender=%1
SET /A ender+=counter
::read lines one by one
FOR /F "usebackq delims=" %%a IN (`DIR /B /ON`) DO (
REM make sure we do not rename any of the working files
IF NOT "%%~a"=="%~nx0" (
SET /A counter+=1
RENAME "%%~a" "!counter:~1!%%~xa"
ECHO Renamed "%%~a" to "!counter:~1!%%~xa"
)
REM exit when we have run enough
IF "!counter!"=="!ender!" GOTO :EOF
)
GOTO :EOF
:usage
ECHO Usage: renamer NUMFILES
You can also see that I made some other enhancements, like making sure the file name is enclosed in double quotes, and using GOTO :EOF instead of GOTO exit (:EOF is a special pre-defined label that points at the end of the batch script so you don't need to define your own).