Sometimes I press Y it goes to :no
And sometimes I press N it goes to :yes
What am I doing wrong?
Now the loop should go 3 times that's not the problem
Only the call is made is never good.
Hope someone can help me
CD %INSTALLDIR%
SET test=
FOR /f %%a in ('dir /b /o:-n') do (
SET test=%%a
ECHO Generate a answer file for %test%?
set INPUT=
set /P INPUT=[Y/N]:
IF /I '%INPUT%'=='y' call :yes
IF /I '%INPUT%'=='n' call :no
)
goto end
:yes
cd %test%
SET APPNAME=<%test%.options
for /f "tokens=1*" %%b in (%test%.options) do set OPTIONS=%%b
echo %APPNAME%
echo %OPTIONS%
goto end
:no
echo Skipping %%a
goto end
:end
ECHO NEXT
Every environment variable referenced with %VariableName% within a command block starting with ( and ending with matching ) is expanded during preprocessing of entire command block by Windows command interpreter before executing the command which finally executes the already preprocessed command block.
This means %INPUT% is replaced by the value of environment variable INPUT before command FOR is executed at all. The environment variable INPUT is not defined in the batch file above command FOR and so the comparisons in the command block depend on existence of this environment variable and its current value on starting the batch file.
Run in a command prompt window set /? and read the help output into the console window. The usage of delayed environment variable expansion is explained by the help on an IF and a FOR example on which command blocks are used usually.
But there is a better solution for this task then enabling delayed expansion. Instead of using set /P INPUT=[Y/N]: the command CHOICE is used which exits with an exit code assigned to ERRORLEVEL depending on key pressed by the user. In this case ERRORLEVEL is 1 if the user presses Y or y as being the first specified option or 2 if N or n is pressed by the user. Other values are not possible.
See also Microsoft support article Testing for a Specific Error Level in Batch Files explaining how ERRORLEVEL can be evaluated in a batch file even within a command block without usage of delayed expansion.
cd /D "%INSTALLDIR%"
for /F %%I in ('dir /AD /B /O:-N 2^>nul') do (
%SystemRoot%\System32\choice.exe /C YN /N /M "Generate an answer file for %%I [Y/N]? "
if errorlevel 2 (echo Skipping %%I) else call :GetOptions "%%I"
)
goto :EOF
:GetOptions
cd /D "%~1"
set APPNAME=<"%~1.options"
for /F "usebackq" %%J in ("%~1.options") do set "OPTIONS=%%J"
echo %APPNAME%
echo %OPTIONS%
goto :EOF
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
cd /?
choice /?
dir /?
echo /?
for /?
goto /?
if /?
set /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of < and 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
See also Where does GOTO :EOF return to?
Related
I'm trying to write a batch file that returns the most recent file in a directory without using a for loop. I tried a lot but it's not working.
So is there a approach that we can get the most recent file without using for loop?
#echo off
cd D:\Applications
for /f "delims=" %%i in ('dir /b/a-d/od/t:c') do set RECENT="%%~nxi"
echo ..... starting jar........
start java -jar %RECENT%
echo ....jar started.....
exit 0
The execution gets stuck at start java and it does not go to next line or exit 0.
There can be used the following code using command FOR:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
cd /D "D:\Applications" 2>nul || (echo ERROR: Directory D:\Applications does not exist.& goto EndBatch)
for /F "eol=| delims=" %%i in ('dir /A-D /B /O-D /TC 2^>nul') do set "RECENT=%%i" & goto StartJava
echo WARNING: Could not find any file in directory: "%CD%"& goto EndBatch
:StartJava
if exist %SystemRoot%\System32\where.exe %SystemRoot%\System32\where.exe java.exe >nul 2>nul
if errorlevel 1 echo ERROR: Could not find java.exe. Check environment variable PATH.& goto EndBatch
echo ..... Starting jar .....
start "Running %RECENT%" java.exe -jar "%RECENT%"
if not errorlevel 1 echo ..... jar started .....
:EndBatch
if errorlevel 1 echo/& pause
endlocal
There is some error handling also added to the code.
Please note that the creation date is the date of a file on being created in the current directory. So if a file is copied from directory X to directory Y, its last modification date is not modified, but the file has a new creation date in directory Y which is newer than its last modification date.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cd /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
set /?
setlocal /?
start /?
where /?
See also:
Single line with multiple commands using Windows batch file
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
I'm not sure why you don't want to use the most powerful command in cmd, but for the sake of answering your question:
dir /o-d /b "C:\my folder\*" >tmp
<tmp set /p "latest="
del tmp
echo the latest file is %latest%
I have come up with the following code which starts minimized, waits 5 seconds (for slow PC) deletes temp files after and should automatically close, but for some reason, automatic close is not working, .bat file stays minimized.
I tried using exit command but it has 0 effect because goto :EOF prevent it from execution, but if I will remove goto :EOF script won't delete temp files
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
PING localhost -n 5 >NUL
#echo off
setlocal
call :Clear_Folder %SystemRoot%\TEMP
pushd C:\Users
for /d %%k in (*) do if exist "%%k\AppData\Local\Temp" call :Clear_Folder "%%k\AppData\Local\Temp"
popd
endlocal
goto :EOF
:Clear_Folder
pushd "%~1"
for /d %%i in (*) do rd /s /q "%%i"
del /f /q *
popd
goto :EOF
exit
I'm looking forward to fix last step auto close, all other features work fine, the script starts minimized, it deletes temp files but after all of this it won't close itself and it stays minimized.
The reason your minimized script is not closing at the end is that you started the script directly, instead of as an argument to cmd.exe with it's /C option. When you run your script directly via Start, cmd.exe is run using the /K option with your batch file as its argument. When the /K option is used, as explained from running cmd /?, the window remains open upon completion of the command. To close that window you need to explicitly exit the cmd.exe instance:
Here's my take on what you intended to do:
#If Not Defined IS_MINIMIZED Set "IS_MINIMIZED=1"&Start "" /Min "%~f0"&Exit
#Echo Off
Timeout 5 /NoBreak>NUL
Call :Clear_Folder "%SystemRoot%\TEMP"
For /D %%k In ("C:\Users\*")Do If Exist "%%k\AppData\Local\Temp\" Call :Clear_Folder "%%k\AppData\Local\Temp"
Exit
:Clear_Folder
PushD "%~1" 2>NUL||Exit /B
RD /S /Q "%~1" 2>NUL
PopD
GoTo :EOF
If there's no other content beneath this, you can also remove GoTo :EOF
The goto eof statements are explicitly going to end of file, skipping anything else, including your exit statement. You therefore need to change or remove it, in this instance I added a different label to goto which has only exit in the label. The second loop does not require the goto as it will fall through the label regardless:
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
timeout 5>nul
#echo off
setlocal
call :Clear_Folder %SystemRoot%\TEMP
pushd C:\Users
for /d %%k in (*) do if exist "%%k\AppData\Local\Temp" call :Clear_Folder "%%k\AppData\Local\Temp"
popd
endlocal
exit
:Clear_Folder
pushd "%~1"
for /d %%i in (*) do rd /s /q "%%i"
del /f /q *
popd
To explain: goto :eof is a predefined label that will exit the current script or subroutine. It therefore will skip anything in the script and simply stops executing any further instructions.
See this link on ss64
The problem is the first line not explicitly starting cmd.exe with option /C to execute the batch file once again with a separate command process with minimized window.
#echo off
if defined IS_MINIMIZED goto ClearFolders
set "IS_MINIMIZED=1"
start "Clear Folders" /min %ComSpec% /C "%~f0" %*
goto :EOF
:ClearFolders
call :Clear_Folder "%SystemRoot%\TEMP"
if defined TEMP call :Clear_Folder "%TEMP%"
for /D %%k in (C:\Users\*) do if exist "%%k\AppData\Local\Temp" call :Clear_Folder "%%k\AppData\Local\Temp"
goto :EOF
:Clear_Folder
pushd "%~1"
if errorlevel 1 goto :EOF
rd /Q /S "%~1" 2>nul
popd
goto :EOF
See also my answer on How to delete files/subfolders in a specific directory at the command prompt in Windows? It explains why rd /Q /S "%~1" 2>nul is enough to delete all subfolders and files in directory of which path is passed with argument 1 to the subroutine Clear_Folder if that directory is really existing and pushd successfully made it the current directory for the command process processing the batch file.
See also: Where does GOTO :EOF return to?
What happens after execution of first goto :EOF depends on how this batch file was started and in which environment.
A double click on a batch file results in starting the Windows command processor cmd.exe for processing the batch file with using implicit option /C to close command process after execution of the batch file. In this case the first goto :EOF results in closing initially opened console window as the Windows command process processing the batch file initially also closes.
Opening first a command prompt window results in starting cmd.exe with using implicit option /K to keep command process running after execution of a command line like executing this batch file. In this case the console window remains open after execution of first goto :EOF as the command process keeps running for further command executions by the user.
The first goto :EOF could be replaced by command exit to always exit the command process independent on how cmd.exe initially processing the batch file was started and independent on the calling hierarchy. So the usage of exit is not advisable in case of this batch file is called from another batch file which does for example more hard disk cleanup operations.
Hello and firstly I would like to apologize for this post if it was already answered before. I spent the last 4 hours searching Stackoverflow and Google.
I have a gamesettings.ini file I would like to edit via batch file. I need to perform this over many PCs, so I would like to keep the other settings besides 2 lines in the file.
The two lines im trying to change are:
CustomVoiceChatInputDevice=Default Input
CustomVoiceChatOutputDevice=Default Output
I tried a few batch scripts I found on Stackoverflow, but they only work if I define the full line. Since every user has different options set, i need the script to just take the start of the line. Just "CustomVoiceChatInputDevice" for example.
Here's an example code I used, thanks to #jsanchez. This script doesn't work unless I type out the whole line:
Thank you for your time!!
#echo off
::Use the path from whence the script was executed as
::the Current Working Directory
set CWD=C:\
::***BEGIN MODIFY BLOCK***
::The variables below should be modified to the
::files to be changed and the strings to find/replace
::Include trailing backslash in _FilePath
set _FilePath=C:\Users\NEOSTORM\AppData\Local\RedDeadGame\Saved\Config\WindowsClient\
set _FileName=GameUserSettings.ini
::_WrkFile is the file on which the script will make
::modifications.
set _WrkFile=GameUserSettings.bak
set OldStr="CustomVoiceChatInputDevice"
set NewStr="CustomVoiceChatInputDevice=Line (Astro MixAmp Pro Game)"
::***END MODIFY BLOCK***
::Set a variable which is used by the
::search and replace section to let us
::know if the string to be modified was
::found or not.
set _Found=Not found
SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION
if not exist "%_FilePath%%_FileName%" goto :NotFound
::If a backup file exists, delete it
if exist "%_FilePath%%_WrkFile%" (
echo Deleting "%_FilePath%%_WrkFile%"
del "%_FilePath%%_WrkFile%" >nul 2>&1
)
echo.
echo Backing up "%_FilePath%%_FileName%"...
copy "%_FilePath%%_FileName%" "%_FilePath%%_WrkFile%" /v
::Delete the original file. No worries, we got a backup.
if exist "%_FilePath%%_FileName%" del "%_FilePath%%_FileName%"
echo.
echo Searching for %OldStr% string...
echo.
for /f "usebackq tokens=*" %%a in ("%_FilePath%%_WrkFile%") do (
set _LineChk=%%a
if "!_LineChk!"==%OldStr% (
SET _Found=Found
SET NewStr=!NewStr:^"=!
echo !NewStr!
) else (echo %%a)
)>>"%_FilePath%%_FileName%" 2>&1
::If we didn't find the string, rename the backup file to the original file name
::Otherwise, delete the _WorkFile as we re-created the original file when the
::string was found and replaced.
if /i "!_Found!"=="Not found" (echo !_Found! && del "%_FilePath%%_FileName%" && ren "%_FilePath%%_WrkFile%" %_FileName%) else (echo !_Found! && del "%_FilePath%%_WrkFile%")
goto :exit
:NotFound
echo.
echo File "%_FilePath%%_FileName%" missing.
echo Cannot continue...
echo.
:: Pause script for approx. 10 seconds...
PING 127.0.0.1 -n 11 > NUL 2>&1
goto :Exit
:Exit
exit /b
Each setting within your .ini file identifies the name of the setting. So the order of the lines should not may not matter.
If the line order is meaningless, then all you need do is use FINDSTR /V to remove the old values, and then simply append the new values. In the script below I modify both values at the same time.
#echo off
setlocal enableDelayedExpansion
set "iniLoc=C:\Users\NEOSTORM\AppData\Local\RedDeadGame\Saved\Config\WindowsClient"
set "iniFile=%iniLoc%\GameUserSettings.ini"
set "iniBackup=%iniLoc%\GameUserSettings.bak"
set "CustomVoiceChatInputDevice=Line (Astro MixAmp Pro Game)"
set "CustomVoiceChatOutputDevice=Some new value"
>"%iniFile%.new" (
findstr /vb "CustomVoiceChatInputDevice= CustomVoiceChatOutputDevice=" "%iniFile%"
echo CustomVoiceChatInputDevice=!CustomVoiceChatInputDevice!
echo CustomVoiceChatOutputDevice=!CustomVoiceChatOutputDevice!
)
copy "%iniFile%" "%iniBackup%"
ren "%iniFile%.new" *.
It would be slightly faster to create the backup file via rename instead of copy, but then there would be a brief moment where the ini file does not exist.
Windows command processor is not designed for editing text files, it is designed for running commands and applications.
But this text file editing/replacing task can be nevertheless done with cmd.exe (very slow):
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=%LOCALAPPDATA%\RedDeadGame\Saved\Config\WindowsClient\GameUserSettings.ini"
set "TempFile=%TEMP%\%~n0.tmp"
if not exist "%FileName%" goto EndBatch
del "%TempFile%" 2>nul
for /F delims^=^ eol^= %%A in ('%SystemRoot%\System32\findstr.exe /N "^" "%FileName%"') do (
set "Line=%%A"
setlocal EnableDelayedExpansion
if not "!Line:CustomVoiceChatInputDevice=!" == "!Line!" (
echo CustomVoiceChatInputDevice=Line (Astro MixAmp Pro Game^)
) else if not "!Line:CustomVoiceChatOutputDevice=!" == "!Line!" (
echo CustomVoiceChatOutputDevice=Line (Astro MixAmp Pro Game^)
) else echo(!Line:*:=!
endlocal
) >>"%TempFile%"
rem Is the temporary file not binary equal the existing INI file, then move
rem the temporary file over existing INI file and delete the temporary file
rem if that fails like on INI file currently opened by an application with
rem no shared write access. Delete the temporary file if it is binary equal
rem the existing INI file because of nothing really changed.
%SystemRoot%\System32\fc.exe /B "%TempFile%" "%FileName%" >nul
if errorlevel 1 (
move /Y "%TempFile%" "%FileName%"
if errorlevel 1 del "%TempFile%"
) else del "%TempFile%"
:EndBatch
endlocal
See the answer on How to read and print contents of text file line by line? for an explanation of the FOR loop.
Please note the caret character ^ left to ) in the two lines to output. A closing parenthesis outside a double quoted argument string must be escaped here with ^ as otherwise ) would be interpreted by Windows command processor as end of command block and not as literal character to output by command ECHO. Other characters with special meaning for cmd.exe on parsing a command line or an entire command block like &|<> must be also escaped with ^ on ECHO command lines.
Please take also a look on Wikipedia article about Windows Environment Variables. It is highly recommended to use the right predefined environment variables for folder paths like local application data folder.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~n0 ... batch file name without path and file extension.
del /?
echo /?
endlocal /?
fc /?
findstr /?
for /?
if /?
move /?
rem /?
set /?
setlocal /?
I am new to batch scripting
I am supposed to write a batch file to read a text file and two command line parameter say ,"task" and "choice".There can be two values for choice-"enable" and "disable"
Now i would want to input the file line by line and match the starting of line with "task" command line argument entered followed by a colon(:) followed by anything .
Now if the choice is "enable" then i have to put ":N" in the respective lines in which the task matches if it doesnt contain a :N already
My text file would contain entries like:
24343:abc:dsd:N
233:zxzxzc
2344:cxzc:xzc
and if i run a command like
myscript.bat 2344 enable
the output of the script should be that the file should be
24343:abc:dsd:N
233:zxzxzc
2344:cxzc:xzc:N
I have been trying to write the code for this for two whole days but still havent been successful.
After all the reading,this is what i have written till now
#echo off
set /A taskname= %1
set choice= %2
FOR /F "tokens=* delims=" %%x in (testdoc.txt) do (
echo %x%|findstr /R "^'%1'.*[^:][^N]$"
if errorlevel 1 (echo does not contain) else (echo contains)
)
In this,i was trying to compare line by line with the regex but it doesnt work as intended.
Any help would be appreciated
Thanks
Regular expression replaces are not possible with pure usage of Windows command line interpreter cmd.exe or the console applications installed with Windows. This would require usage of a scripting language/interpreter with support for regular expression replaces in files like PowerShell or JScript which would be most likely better choices for this task.
However, a pure batch file solution is also possible for this task as it can be seen on commented batch code below with lots of extra features.
#echo off
set "TempFile=
rem Is first parameter /? for getting help?
if "%~1" == "/?" goto ShowHelp
rem Is the batch file not started with any none empty parameter?
if not "%~1" == "" (
rem Does the first parameter not consist of only digits 0-9?
for /F "delims=0123456789" %%I in ("%~1") do goto ShowHelp
)
rem Is there also specified a second parameter?
if not "%~2" == "" (
rem Is the second parameter neither enable nor disable (case-insensitive)?
if /I not "%~2" == "disable" if /I not "%~2" == "enable" goto ShowHelp
)
rem Setup a local environment for this batch file.
setlocal EnableExtensions DisableDelayedExpansion
rem Define the name of the text file without or with path to modify.
rem Define the name of the temporary file needed to modify the file.
set "TextFile=TextFile.txt"
set "TempFile=%TEMP%\%~n0.tmp"
rem Does the text file to modify exist at all?
if not exist "%TextFile%" goto MissingFile
rem Was a task number specified on starting this batch file?
if not "%~1" == "" set "TaskNumber=%~1" & goto FindTask
rem Prompt the user for the task number and make sure that the user really
rem enters a number by verifying user input using a very secure method.
:PromptNumber
set "TaskNumber="
set /P "TaskNumber=Enter task number: "
if not defined TaskNumber goto PromptNumber
setlocal EnableDelayedExpansion
for /F "delims=0123456789" %%I in ("!TaskNumber!") do endlocal & goto PromptNumber
endlocal
:FindTask
rem Does the file to modify contain the number at beginning of a
rem line as specified with first parameter and followed by a colon?
%SystemRoot%\System32\findstr.exe /B /L /M /C:"%TaskNumber%:" "%TextFile%" >nul 2>&1
if errorlevel 1 goto MissingNumber
rem Has the user specified the action to perform as second parameter.
if /I "%~2" == "enable" set "TaskAction=1" & goto ModifyFile
if /I "%~2" == "disable" set "TaskAction=2" & goto ModifyFile
rem Prompt the user for the action to perform.
%SystemRoot%\System32\choice.exe /N /M "Press Y to enable or N to disable task: "
set "TaskAction=%ERRORLEVEL%"
rem Copy the file with ignoring empty lines and lines starting with a
rem semicolon to temporary file with modifying all lines starting with
rem the specified task number according to specified action to perform.
rem But delete the temporary file before if existing by chance.
:ModifyFile
del "%TempFile%" 2>nul
set "FileModified="
for /F "usebackq tokens=1* delims=:" %%I in ("%TextFile%") do (
if not "%%I" == "%TaskNumber%" (
echo %%I:%%J>>"%TempFile%"
) else (
set "TextLine=%%I:%%J"
call :ModifyLine
)
)
rem Was no line modified on copying all the lines to temporary file?
if not defined FileModified del "%TempFile%" & goto EndBatch
rem Move the temporary file over the text file to modify.
move /Y "%TempFile%" "%TextFile%" 2>nul
rem Was the text file overwritten by command MOVE?
if not errorlevel 1 goto EndBatch
rem Inform the user that the text file to modify could not be
rem modified because of being read-only or missing appropriate
rem NTFS permissions or a sharing access violation occurred.
del "%TempFile%"
for /F %%I in ("%TextFile%") do set "TextFile=%%~fI"
echo/
echo ERROR: "%TextFile%" could not be modifed.
echo/
echo Please make sure the file has not read-only attribute
echo set, is not opened in any application and you have
echo the necessary permissions to overwrite this file.
goto HaltBatch
rem This is a subroutine which modifies a line with right task
rem number according to action to perform and outputs this line
rem into the temporary file. It records also if the line needed
rem to be modified at all.
:ModifyLine
if %TaskAction% == 1 (
if not "%TextLine:~-2%" == ":N" (
set "TextLine=%TextLine%:N"
set "FileModified=1"
)
) else (
if "%TextLine:~-2%" == ":N" (
set "TextLine=%TextLine:~0,-2%"
set "FileModified=1"
)
)
>>"%TempFile%" echo %TextLine%
goto :EOF
rem Get name of file with full path which works also for not existing
rem file and inform the user about missing file to modify with full
rem path to see also where this batch file expected it on execution.
:MissingFile
for /F %%I in ("%TextFile%") do set "TextFile=%%~fI"
echo/
echo ERROR: "%TextFile%" does not exist.
goto HaltBatch
:MissingNumber
rem The specified number does not exist in the file to modify
rem at beginning of a line. Inform the user about this error.
echo/
echo ERROR: %TaskNumber% not found in file "%TextFile%".
goto HaltBatch
:ShowHelp
echo/
echo Usage: %~nx0 [task] [disable ^| enable]
echo/
echo task ...... number of the task to enable or disable.
echo disable ... disable the specified task.
echo enable .... enable the specified task.
echo/
echo %~nx0 can be also started without any parameter.
echo In this case the task number and the action to perform
echo can be entered during the execution of the batch file.
:HaltBatch
echo/
pause
echo/
:EndBatch
if defined TempFile endlocal
The command line set "TextFile=TextFile.txt" must be modified to your environment.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
choice /?
del /?
echo /?
endlocal /?
findstr /?
for /?
goto /?
if /?
move /?
pause /?
rem /?
set /?
setlocal /?
Further read following:
DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/
Microsoft article about Using Command Redirection Operators
Stack Overflow answer on Where does GOTO :EOF return to?
Stack Overflow answer on Single line with multiple commands using Windows batch file
I have batch file that writes to the text file with the records. Each of this record needs to be processed from the file. For example if Name == KD then go to step 1 else continue with the next steps.
The issue after it goes to step 1, it exits the file. I need to come back to the next record to continue processing with DF. I did add label to the section to come back but it keeps processing only KD record.
Text file example:
Line Name Container
1 KD 123
2 DF 657
Code:
set txtfilepath=C:\Temp\Test.txt
set /a cnt=0
for /f %%a in ('type "%txtfilepath%"^|find "" /v /c') do set /a cnt=%%a
echo %txtfilepath% has %cnt% lines
for /f "skip=1 tokens=1,2,3,4,5* delims=,] " %%a in ('find /v /n "" ^< %txtfilepath%') do (
echo.%%b - this displays variable fine.
if %%b==DF (
set result=true
) else (
goto donotexecute
)
echo I am in true loop.
:donotexecute
echo i am in do not import loop
)
:Done
So the code goes in the donotexecute label and then I have no way to go back to my initial for loop to continue with the next line in the text file.
First, don't use set /a (evaluate arithmetic expression) if you just want to assign a value to an environment variable.
Environment variables are always of type string. On an arithmetic expression each number specified directly or hold by an environment variable is converted temporarily to a 32-bit signed integer for evaluation of the expression and the integer result is finally converted back to a string stored in the specified environment variable. So much faster is assigning the number string directly to the environment variable.
Second, Windows command processor does not support labels within a FOR loop. You need to use subroutines.
#echo off
set "txtfilepath=C:\Temp\Test.txt"
rem Don't know why the number of lines in the files must be determined first?
set "cnt=0"
for /F %%a in ('type "%txtfilepath%" ^| %SystemRoot%\System32\find.exe "" /v /c') do set "cnt=%%a"
echo %txtfilepath% has %cnt% lines.
for /F "usebackq skip=1 tokens=1-5* delims=,] " %%a in ("%txtfilepath%") do (
if "%%b" == "DF" (
call :ProcessDF "%%c"
) else if "%%b" == "KD" (
call :ProcessKD "%%c"
)
)
echo Result is: %result%
rem Exit processing of this batch file. This command is required because
rem otherwise the batch processing would continue unwanted on subroutine.
goto :EOF
rem This is the subroutine for name DF.
:ProcessDF
echo Processing DF ...
set "result=true"
echo Container is: %~1
goto :EOF
rem The command above exits subroutine and batch processing continues
rem on next line below the command line which called this subroutine.
rem This is the subroutine for name KD.
:ProcessKD
echo Processing KD ...
echo Container is: %~1
rem Other commands to process.
goto :EOF
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
find /?
for /?
goto /?
if /?
rem /?
set /?
type /?
exit /B could be also used everywhere where goto :EOF is used as this is exactly the same. Run in a command prompt window exit /? for details. Sometimes on larger batch files it makes sense to use for example exit /B where used to exit processing of batch file and goto :EOF where used to just exit a subroutine.