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...
Related
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
)
)
I have created command script for reading %N% lines from file. The problem is I can't delete " from anywhere in all text streams when I work with file's text. " deletion is very needed because if file's text line have substring like "text" and text have special chars or even worse, script code, then the script crashes or works not proper way (including script control capturing by programmer who specially composed the text).
If I can't delete " from the text stream(s), then I just want to identify, that the file (or it's first %N% lines, including empty lines) contains at least one " char.
Any thoughts are appreciated, including any file preprocessing. But main aim is script speed.
for /f "skip=2 delims=" %%a in ('find /v /n "" "file" 2^>nul') do set "v=%%a"&call :v&if not errorlevel 1 goto FURTHER1
goto FURTHER2
:v
for /f "delims=[]" %%a in ("%v%") do set "line%%a=%v:*]=%"&if %%a lss %N% (exit /b 1) else exit /b 0
#ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q39558311.txt"
SET "tempfilename1=%sourcedir%\q39558311#.txt"
>"%tempfilename1%" ECHO("
SET /a linefound=0
FOR /f "tokens=1 delims=:" %%a IN ('findstr /n /g:"%tempfilename1%" "%filename1%"') DO (
IF %%a gtr 2 SET /a linefound=%%a&GOTO report
)
:report
ECHO quote found AT line %linefound%
DEL "%tempfilename1%"
GOTO :EOF
You would need to change the setting of sourcedir and filename1 to suit your circumstances.
tempfile1 can be any name - it's just a temporary file; I chose that particular name for convenience.
I used a file named q39558311.txt containing some dummy data for my testing.
Essentially, create a file containing a single quote on a single line *tempfile1) then use findstr with the /g:filename option to read in the target strings to find. When findstr finds the line, it numbers it and outputs line_number:line found. Using : as a delimiter, token 1 of this line is the line number.
I don't understand why you've used the skip=number in your code. Do you intend to skip testing the first 2 lines of the target file?
the IF %%a gtr 2 tests the line number found. If it is greater than 2, then the variable linefound is set and the for loop is terminated.
I chose to initialise linefound to zero. It will remain zero if no " is found in lines 2..end. Equally, you could clear it and then it will be defined (with a value of first-line-found-with-quote-greater than-2) and no defined on not found.
I can only identify ", but not delete. Waiting for your suggestions on it!
>nul 2>&1 findstr /m \" "file"
if not errorlevel 1 echo double quote found!
Hi I want some basic help with Windows commands to automate some of my work.
I have a folder in which I get some files, I need to run a fix process in order to correct the file contents.
#echo off
setlocal
set /a "n=0, limit=3"
>"testfile1.txt" (
for /f %%F in ('dir /o-d /b *_SourceFile_*.csv') do (
set %x= echo %%F |findstr /i/v "\.fixed.csv"
if %x% not nul
(
FixFileWithWinFormat.exe %%F
2>nul set /a "n+=1, 1/(limit-n)"||goto :break
)
)
)
:break
echo 'competed'
This bit of code above if I comment out the %x is working the if condition is not making it to work. Don't know why. It could be silly.
set %x= echo %%F |findstr /i/v "\.fixed.csv"
if %x% not nul
These two lines are incorrect. It's better to state what the code is intended to do, otherwise we're guessing.
The set statement can't be used to set an environment variable in that manner - it's very simple, set var=string and %x is an invalid variable to set.
The not nul idea can be accomplished by if not defined x - but no %s.
So - assuming you wish to execute the following parenthesised statement-sequence if the filename in %%f is not found in the file, then
findstr /i "%%f" ".\fixed.csv" >nul
if errorlevel 1 (your statementsequence in parentheses)
should do the task. I'm not sure of the filename fixed.csv here. \.fixed.csv will locate a filename .fixed.csv in the root directory, whereas .\fixed.csv will locate a file fixed.csv in the current directory (and hence the .\ is redundant.)
findstr will find the string contained in %%f in the file, with /i making the seach case-insensitive. >nul redirects any output to nowhere. errorlevel is set to 0 if the text is found, non-zero otherwise.
if errorlevel 1 means "if errorlevel is 1 or greater". Note that if errorlevel 0 means "if errorlevel is 0 or greater" (ie. always, for all intents and purposes) hence to detect errorlevel 0 (ie "text found" you need if not errorlevel 1)
and the opening parenthesis must be on the same physical line as the if
(not sure about your terminating condition; seems to be attempting to force a divide-by-zero after limit iterations. Don't have the time to test atm - soz)
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).