cmd for loop error 'in was unexpected at this time' - batch-file

I'm writing a cmd file that will loop through all the directories in a given directory and generate swagger code for each file in each directory. I cannot get the correct syntax for the 'for' loops.
cd C:\Users\Sora Teichman\Documents\APIJsonModels\models
for /D %%A in ("C:\Users\Sora Teichman\Documents\APIJsonModels\models\*") do (
set fileFolder=%cd%
echo %fileFolder%
for /F %%G in (fileFolder) do (
set filePath=%f
echo %filePath%
java -jar .\swagger-codegen-cli.jar generate -i filePath -l csharp-dotnet2 -o fileFolder
)
)
I'm getting 'in was unexpected at this time' at the outer for loop. I tried using a variable for the folder path, I tried with the asterisk and without, I tried ('dir "C:\Users\Sora Teichman\Documents\APIJsonModels\models"').
The ss64 does not provide enough detail for my scenario.
What is the correct syntax for this?
I know that I need double %% for the parameters because this is in a .cmd file, there are many question online for this issue :).
For context, I am running this command file from a .csproj file using an <Exec Command="codeGenerator.cmd"/> tag.
Edit: #Stephan pointed out that I needed to set my variables correctly, but now I need help with the inner loop. When I use the fileFolder variable, the error I get is 'The system cannot find the file C:\Users\Sora.' It is getting stuck on the space in the folder path.

I figured it out on my own thanks to #Stephan's comment. Here's the working code:
set jsonFoldersPath="C:\Users\Sora Teichman\Documents\APIJsonModels\models\*"
#echo off
setlocal enabledelayedexpansion
FOR /D %%f in (%jsonFoldersPath%) do (
set fileFolder=%%f
cd !fileFolder!
for %%a in (*) do (
set fileName=%%a
set filePath=!fileFolder!\!fileName!
cd C:\Users\Sora Teichman\Documents\AmazonAPIGenerator
java -jar .\swagger-codegen-cli.jar generate -i "!filePath!" -l csharp-dotnet2 -o "C:\Users\Sora Teichman\Documents\AmazonAPIGenerator\AmazonGeneratedModels" -c "C:\Users\Sora Teichman\Documents\AmazonAPIGenerator\config.json"
)
)
You need to enable delayed expansion for variables using setlocal enabledelayedexpansion so that they only evaluate at execution in the loop; read an explanation here: How do SETLOCAL and ENABLEDELAYEDEXPANSION work?
I did not end up using a variable for the -o output directory parameters for Swagger because Swagger organizes the code on its own; it generates API, Client and Model namespaces which I customized using a config.json file and the -c parameter.
I also plan to replace the hardcoded paths with relative ones.

Related

How to filter on exact file extension?

I have .las and .lasx files which have the same file name in a DATA folder. I am trying to apply processes on the *.las files only. But it seems that the wildcard pattern *.las also includes *.lasx files:
for %%f in ("%DATA_PATH%\*.las") do
or
lasground -i "%DATA_PATH%\*.las" -merged
The parameter before -merged is supposed to be the list of my *.las files only, but during my tests it always includes the *.lasx files.
Any idea about how to get all my .las files without getting the .lasx ones?
After providing the documentation and the actual program you are using I would give these two examples a try.
Make a variable with all the file names.
#ECHO OFF
for %%G in ("%DATA_PATH%\*.las") do (
IF /I "%%~xG"==".las" call set list=%%list%% "%%G"
)
lasground -i %list% -merged
Make a list of files and use the -lof option.
#ECHO OFF
(for %%G in ("%DATA_PATH%\*.las") do (
IF /I "%%~xG"==".las" echo %%G
)
)>List.txt
lasground -lof List.txt -merged
The Where command is a simpler way to filter this directly, i.e. output only the extension specified:
#Where "%DATA_PATH%":*.las 2>Nul >"LasOnly.txt"
You can then use "LasOnly.txt" as input to lasground using the -lof option as already advised:
#lasground -lof "LasOnly.txt" -merged

Pandoc Windows batch file builds wrong path openBinary file does not exist

THE ISSUE
This may just stem from a lack of deep understanding of Windows batch file coding.
I am trying to write a simple one-line batch file that will process every file in a directory using pandoc to convert all doc or docx (MS Word) files to markdown (.md) files. When I run my batch file I get the following error:
pandoc: C:_ALL\_ALL\accomp\testing-accomp-2017.05\20170505.md: openBinaryFile: does not exist (No such file or directory)
I get one of these errors for each file in the directory (around 25, or so).
The directory I'm running my command in looks like this:
C:\_ALL\!accomp\testing-accomp-2017.05
As you can see, for some reason the _ALL is appearing twice. The path it is showing me isn't right for some reason and I'm not sure if it is a pandoc issue or a CMD batch file programming issue.
MY CODE
Here is the code for my batch file:
#echo OFF
:: [Not sure what this does, but have read that it is necessary]
setlocal enabledelayedexpansion
:: MAIN
FOR /r "." %%i IN (*.doc *.docx) DO pandoc -f rst -t markdown "%%~fi" -o "%%~dpni.md"
:: End with a pause so user can copy any text from screen.
ECHO. Done. Press any key to terminate program
PAUSE>NUL
Now, I'm not certain what all these lines of code do, and they may be entirely unnecessary for all I know. However, the main and most important code here is the one that starts with For ..., which is inspired by this Stack Overflow post:
Batch processing Pandoc conversions in Windows
WHAT I'VE TRIED ALREADY
Basically there are about four variations of the same answer in the above linked post and I've tried each of those variations.
The error is caused by delayed expansion and the exclamation mark ! in directory name !accomp.
The command line to execute by FOR expands during execution with file 20170505.doc to:
pandoc -f rst -t markdown "C:\_ALL\!accomp\testing-accomp-2017.05\20170505.doc" -o "C:\_ALL\!accomp\testing-accomp-2017.05\20170505.md"
This command line is parsed by Windows command processor a second time before execution because of enabled delayed environment variable expansion, searching for !variable! reference and replacing them with value of referenced variables.
The string !accomp\testing-accomp-2017.05\20170505.doc" -o "C:\_ALL\! is completely misinterpreted here because of the exclamation marks. So finally executed is:
pandoc -f rst -t markdown "C:\_ALL\\_ALL\accomp\testing-accomp-2017.05\20170505.md"
And the file C:\_ALL\\_ALL\accomp\testing-accomp-2017.05\20170505.md does not exist.
The solution is removing setlocal enabledelayedexpansion as not needed here because of no environment variable used on FOR command line.
#ECHO OFF
FOR /r "." %%i IN (*.doc *.docx) DO pandoc.exe -f rst -t markdown "%%i" -o "%%~dpni.md"
:: End with a pause so user can copy any text from screen.
ECHO Done. Press any key to terminate program ...
PAUSE>NUL
The loop variable i holds here already the full qualified file name. Therefore "%%~fi" can be replaced by "%%i".
And it is better to use ECHO/ instead of ECHO. although neither . nor / is needed here. See DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ for the reason.

Why is a subfolder with space recognized as file on execution of my batch script?

In my code I'm searching for only files in folder and all subfolders. When the name of subfolder has one blank (space) between the words this subfolder is recognized as a file, too. This is not correct behavior. The parameter /a-d doesn't help here.
#echo on
Setlocal EnableDelayedExpansion
set "input=C:\Users\NekhayenkoO\test\"**
set "output=C:\Users\NekhayenkoO\outputxml\"**
set string1=Well-Formed and valid
set string2=Well-Formed, but not valid
set string3=Not well-formed
set /a loop=0
set /a loop1=0
set /a loop2=0
set /a loop3=0
for /f %%a in ('dir /b /a-d /s %input%') do (
CALL jhove -m PDF-hul -h xml -o %output%\%%~na.xml %%a
if !ERRORLEVEL! EQU 0 (echo Errorlevel equals !errorlevel! )
if !ERRORLEVEL! GEQ 1 (Errorlevel equals !errorlevel! )
set /a loop3+=1
)
The output of the script on running in directory C:\Users\NekhayenkoO\jhove-beta:
Setlocal EnableDelayedExpansion
set "input=C:\Users\NekhayenkoO\test\"**
set "output=C:\Users\NekhayenkoO\outputxml\"**
set string1=Well-Formed and valid
set string2=Well-Formed, but not valid
set string3=Not well-formed
set /a loop=0
set /a loop1=0
set /a loop2=0
set /a loop3=0
for /F %a in ('dir /b /a-d /s "C:\Users\NekhayenkoO\test\"') do (
echo Verarbeite %~na
CALL jhove -m PDF-hul -h xml -o "C:\Users\NekhayenkoO\outputxml\\%~na.xml" "%a"
if !ERRORLEVEL! EQU 0 (echo Errorlevel equals !errorlevel! )
if !ERRORLEVEL! GEQ 1 (Errorlevel equals !errorlevel! )
set /a loop3+=1
)
(
echo Verarbeite 757419577
CALL jhove -m PDF-hul -h xml -o "C:\Users\NekhayenkoO\outputxml\\757419577.xml" "C:\Users\NekhayenkoO\test\757419577.pdf"
if !ERRORLEVEL! EQU 0 (echo Errorlevel equals !errorlevel! )
if !ERRORLEVEL! GEQ 1 (Errorlevel equals !errorlevel! )
set /a loop3+=1
)
Verarbeite 757419577
Errorlevel equals 0
Verarbeite GBV58575165X
Errorlevel equals 0
Verarbeite GBV85882115X
java.lang.ClassCastException: edu.harvard.hul.ois.jhove.module.pdf.PdfSimpleObject cannot be cast to edu.harvard.hul.ois.jhove.module.pdf.PdfDictiona
at edu.harvard.hul.ois.jhove.module.PdfModule.readDocCatalogDict(PdfModule.java:1344)
at edu.harvard.hul.ois.jhove.module.PdfModule.parse(PdfModule.java:521)
at edu.harvard.hul.ois.jhove.JhoveBase.processFile(JhoveBase.java:803)
at edu.harvard.hul.ois.jhove.JhoveBase.process(JhoveBase.java:588)
at edu.harvard.hul.ois.jhove.JhoveBase.dispatch(JhoveBase.java:455)
at Jhove.main(Jhove.java:292)
Errorlevel equals 0
Verarbeite GBV858852357
Errorlevel equals 0
Verarbeite nicht_valide_PDF
Errorlevel equals 0
Verarbeite not_Wellformed_intern
Errorlevel equals 0
Verarbeite pp1788_text
Errorlevel equals 0
Verarbeite Rosetta_Testdatei
Errorlevel equals 0
Verarbeite script
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite GBV58525785X
Errorlevel equals 0
Verarbeite GBV58574517X
Errorlevel equals 0
Drücken Sie eine beliebige Taste . . .
What is jhove?
Oleg Nekhayenko, you have asked several jhove related questions in the last days, but you have always forgotten to explain what jhove is which is important to know for all of your questions.
Therefore I searched in world wide web for jhove, found very quickly the homepage
JHOVE | JSTOR/Harvard Object Validation Environment, read quickly its documentation and command-line interface description and finally downloaded also jhove-1_11.zip from SourceForge project page of JHOVE.
All this was done by me to find out that jhove is a Java application which is executed on Linux and perhaps also on Mac using the shell script jhove and on Windows the batch file jhove.bat for making it easier to use by users.
You could have saved yourself and all readers of your questions a lot of time if you would have written jhove.bat instead of just jhove in your code snippets or at least mentioned anywhere that jhove is a batch file.
Assigning a value/string to an environment variable
I suggest to read first the answer on
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
and next look on these two lines:
set "input=C:\Users\NekhayenkoO\test\"**
set "output=C:\Users\NekhayenkoO\outputxml\"**
I don't know why two asterisks are at end of those 2 command lines. But that does not really matter as both asterisk are ignored on assigning the two paths to the two environment variables.
This can be seen on posted output of the batch file as there is no asterisk output on the lines:
for /F %a in ('dir /b /a-d /s "C:\Users\NekhayenkoO\test\"') do (
CALL jhove -m PDF-hul -h xml -o "C:\Users\NekhayenkoO\outputxml\\757419577.xml" "C:\Users\NekhayenkoO\test\757419577.pdf"
There is no asterisk anywhere. So the environment variables input and output are obviously defined without the asterisks at end which is even good here.
Enclosing directory and file names in double quotes
The help output on running cmd /? in a command prompt window explains in last paragraph on last help page on which characters in a directory or file name double quotes must be used around complete directory/file name.
The space character is the string delimiting character on command line and therefore a directory or file name with a space must be always enclosed in double quotes.
Predefined environment variables on Windows
Opening a command prompt window and running set results in output of all environment variables defined for the the current user account including PATH and PATHEXT as also USERNAME and USERPROFILE.
The Wikipedia article about Windows Environment Variables explains the environment variables predefined by Windows. It is advisable to make use of them in batch files.
Execution of applications and scripts on Windows
If in a command prompt window or in a batch file just the file name of an application or script without file extension and without path is specified, the Windows command interpreter is searching first in current directory and next in all directories of environment variable PATH for a file with specified name having a file extension listed in environment variable PATHEXT. In this case Windows command interpreter is searching for jhove.*.
The values of the environment variables PATH and PATHEXT can be seen on opening a command prompt window and running in this window set path which results in output of all environment variables starting with the case-insensitive interpreted string PATH with their current values.
Next to know is that when Windows command interpreter searches for jhove.*, the NTFS file system returns the file names matching this search pattern sorted alphabetically. So if current directory or any of the directories listed in PATH have for example jhove.bat and jhove.exe, the NTFS file system returns first jhove.bat. This batch file is used by Windows command interpreter as file extension BAT is listed by default in PATHEXT.
But if the file system of the drive with jhove.* files is FAT, FAT32 or ExFat, the file system returns the file names matching the search pattern in order as stored in the file allocation table and therefore unsorted. So in case of a directory contains jhove.bat and jhove.exe on a drive with any FAT file system, it is unpredictable which file is executed by Windows command interpreter on specifying just jhove in a batch file.
For that reason it is always advisable to specify the application or script with file name and at least also with the file extension. And if possible the entire path to the application to run or the script to call should be also specified.
The Windows command interpreter does not need to search around by specifying the name of an application or script file with file extension and with complete path.
See also answer on Where is "START" searching for executables?
Calling a batch file versus running an application
A batch file is a script (text file) interpreted by Windows command interpreter line by line whereby a command block starting with ( and ending with matching ) is interpreted like a subroutine defined on one line.
An application is an executable (binary file) compiled with a compiler for a specific processor or processor family and therefore does not need to be interpreted anymore on execution. It contains already processor instructions (machine code).
Why the command call must be used to run another batch file from within a batch file is explained in detail by the answers on
How to call a batch file that is one level up from the current directory?
In a Windows batch file, can you chain-execute something that is not another batch file?
For that reason it is very important to know what jhove is. It is a batch file and must be therefore called with command call which answers the question How to process 2 for loops after each other in batch?
For help on command call open a command prompt window and run call /?. The output help explains also which placeholders exist to reference arguments of the batch file whereby argument 0 is the name of the batch file.
Which command lines contains jhove.bat?
On unexpected behavior on calling a batch file from another batch file it is important to know the code of the called batch file as well because the error could be in code of called batch file.
Code of jhove.bat as stored in jhove-1_11.zip without instruction comments:
#ECHO OFF
SET JHOVE_HOME=%~dp0
SET EXTRA_JARS=
REM NOTE: Nothing below this line should be edited
REM #########################################################################
SET CP=%JHOVE_HOME%\bin\JhoveApp.jar
IF "%EXTRA_JARS%"=="" GOTO FI
SET CP=%CP%:%EXTRA_JARS
:FI
REM Retrieve a copy of all command line arguments to pass to the application
SET ARGS=
:WHILE
IF %1x==x GOTO LOOP
SET ARGS=%ARGS% %1
SHIFT
GOTO WHILE
:LOOP
REM Set the CLASSPATH and invoke the Java loader
java -classpath %CP% Jhove %ARGS%
Well, this is a not good written batch code for following reasons:
The commands setlocal and endlocal are not used in batch file to control the life time of variables used by this batch file. See answer on change directory command cd ..not working in batch file after npm install for more details. npm.bat is also a not good coded batch file like jhove.bat as it turned out.
The command line SET JHOVE_HOME=%~dp0 defines the environment variable JHOVE_HOME with drive and path of storage location of jhove.bat. The path returned by %~dp0 ends always with a backslash. If jhove*.zip was extracted into a directory with 1 or more space in complete path, care must be taken wherever JHOVE_HOME is finally used to enclose the final string in double quotes.
The command line SET CP=%JHOVE_HOME%\bin\JhoveApp.jar defines the environment variable CP by concatenating path to batch file jhove.bat with a fixed path and name of the Java package. Here is already a small mistake as %~dp0 is a path always ending with a backlash concatenated with a string starting with a backslash. So there are two backslashes finally in path to the Java package file. But Windows kernel handles this error in path and therefore it does not really matter.
The environment variable CP is referenced unmodified with no EXTRA_JARS defined by the user finally on command line java -classpath %CP% Jhove %ARGS%. The error here is %CP% is specified without being enclosed in double quotes which results in unexpected behavior if jhove*.zip was extracted indeed by the user into a directory with 1 or more spaces in complete path.
A percent sign is missing at end of command line SET CP=%CP%:%EXTRA_JARS.
The writer of jhove.bat did not know obviously anything about %* which on usage of last command line instead of %ARGS% makes the WHILE loop above completely useless.
Much better for jhove.bat would be:
#echo off
setlocal EnableExtensions
set "JHOVE_HOME=%~dp0"
set "EXTRA_JARS="
REM NOTE: Nothing below this line should be edited
REM #########################################################################
set "CP=%JHOVE_HOME%bin\JhoveApp.jar"
if not "%EXTRA_JARS%"=="" set "CP=%CP%:%EXTRA_JARS%"
rem Set the CLASSPATH and invoke the Java loader
java.exe -classpath "%CP%" Jhove %*
endlocal
The executable java.exe must be found via environment variable PATH by Windows command interpreter.
Final batch code for usage
I suggest to use the following code for this task in case of jhove.bat should not be modified to above working code:
#echo off
setlocal EnableExtensions
set "InputFolder=%USERPROFILE%\test"
set "OutputFolder=%USERPROFILE%\outputxml"
echo Searching for bin\JhoveApp.jar in:
echo.
set "SearchPath=%CD%;%PATH%"
set "SearchPath=%SearchPath:)=^)%"
for /F "delims=" %%I in ('echo %SearchPath:;=^&ECHO %') do (
echo %%I
if exist "%%~I\bin\JhoveApp.jar" (
set "JHOVE_HOME=%%~I"
goto RunJHOVE
)
)
echo.
echo Error reported by %~f0:
echo.
echo Could not find bin\JhoveApp.jar in current directory and folders of PATH.
echo.
endlocal
pause
goto :EOF
:RunJHOVE
if "%JHOVE_HOME:~-1%" == "\" (
set "CP=%JHOVE_HOME%bin\JhoveApp.jar"
) else (
set "CP=%JHOVE_HOME%\bin\JhoveApp.jar"
)
echo.
echo Using %CP%
md "%OutputFolder%" 2>nul
rem for /F %%I in ('dir /A-D /B /S "%InputFolder%\*" 2^>nul') do (
rem java.exe -classpath "%CP%" Jhove -m PDF-hul -h xml -o "%OutputFolder%\%%~nI.xml" "%%I"
rem )
for /R "%InputFolder%" %%I in (*) do (
java.exe -classpath "%CP%" Jhove -m PDF-hul -h xml -o "%OutputFolder%\%%~nI.xml" "%%I"
)
endlocal
The input and output folder paths are defined without backslash at end and without asterisk using predefined environment variable USERPROFILE.
A slightly modified code written by Magoo in his answer on Find the path used by the command line when calling an executable is used to find Java package of JHOVE. The batch file prints the folders it is searching for in case of the file could not be found which results in an error message and halting batch execution until the user presses any key.
The class path variable CP is created with taking into account if folder path ends with a backslash or not. Folder paths in PATH should be defined without backslash at end, but there are always installers which add folder paths not 100% correct to PATH. However, it does not really matter if the result would be \\ anywhere within a path as Windows kernel handles this. That's the reason why if exist "%%~I\bin\JhoveApp.jar" also always works although this file existence test could be also done with two backslashes in path depending on folder path in PATH.
Next the output folder is created without checking first if the folder is already existing and without checking if folder creation was successful at all.
The batch code contains two solutions for running jhove on each file found recursively in input folder path. The first one is commented out. It would have the advantage to work also for hidden and system files. The second solution does not work for hidden and system files, but this is most likely not necessary here. The second solution is therefore the preferred one.
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.
echo /?
endlocal /?
for /?
goto /?
if /?
md /?
pause /?
set /?
setlocal /?
And read also the Microsoft articles:
Microsoft's command-line reference
Using command redirection operators
Testing for a Specific Error Level in Batch Files

Loop through subfolders of subfolders and execute a command on each file of the last subfolder

Consider this hierarchy:
MainFolder\Sub_Folder1\Original_Files\
\Converted_Files\
\Sub_Folder2\Original_Files\
\Converted_Files\
Now in each ...\Original_Files\ I've a bunch of video files which I'll encode and save to the respective ...\Converted_Files\.
I could do it for one subfolder with this batch code:
#echo off
set "sourcedir=G:\Animation\Anime\OnePiece\Episodes\Main"
set "outputdir=G:\Animation\Anime\OnePiece\Episodes\Converted"
PUSHD "%sourcedir%"
for %%F in (*.mkv) DO ffmpeg -i "%%F" -s 640x480 -map 0 -c:v libx265 "%outputdir%\%%F"
POPD
I've generated a text file with the folder paths of all the subfolders which contains:
G:\Animation\ToConvert\Berserk_1997_The_Complete_Series
G:\Animation\ToConvert\Blue_Exorcist
G:\Animation\ToConvert\Elfen_Lied
Every folder listed in the file has Main and Converted folders within them. I've to loop through all files in Main and save into Converted as you might see in above.
This is something I came up with :
#echo off
for /F "tokens=*" %%A in (f.txt) DO (
set "sourcedir=%A%\Main"
set "outputdir=%A%\Converted"
PUSHD "%sourcedir%"
for %%F in (*.mkv) DO ffmpeg -i "%%F" -s 640x480 -map 0 -c:v libx265 "%outputdir%\%%F"
POPD
) %%A
Running for /F "tokens=*" %A in (f.txt) DO #echo %A gives me the names of the subfolders.
I thought somehow if I could pass the name to some variable and concatenate \Main and \Converted to it, it might work.
But on running the code above from within a command prompt window, it's just switching the current directory from the folder I'm running the batch file to C:\Windows.
How can I run nested loops, one for the subfolders and then chose between working in Main and saving in Converted and the next loop for files in Main?
Your last batch code fails because of
referencing the loop variable A like an environment variable with %A% instead of %%A and
referencing environment variables defined/set within a command block defined with ( and ) requires the usage of delayed expansion enabled before with the command line setlocal EnableDelayedExpansion and using !sourcedir! and !outputdir! instead of %sourcedir% and %outputdir% which are already replaced by current value of the environment variables sourcedir and outputdir (empty string here as not defined before) when Windows command processor parses the entire command block before executing command FOR the first time.
%%A after closing parenthesis at end is unknown for Windows command interpreter and results therefore in an exit of batch processing because of a syntax error.
However, better than your code which requires first the creation of a text file with the folder paths would be the usage of following code:
#echo off
for /D %%D in ("G:\Animation\ToConvert\*") do (
if exist "%%D\Main\*.mkv" (
echo Processing %%D ...
if not exist "%%D\Converted\*" md "%%D\Converted"
for %%I in ("%%D\Main\*.mkv") do (
ffmpeg.exe -i "%%I" -s 640x480 -map 0 -c:v libx265 "%%D\Converted\%%~nxI"
)
)
)
The outer FOR with parameter /D finds just non hidden subfolders within folder G:\Animation\ToConvert and holds in loop variable D the name of the subfolder with full path not ending with a backslash.
The IF condition checks if in the current subfolder there is a folder Main with 1 or more *.mkv files to process. If this condition is true,
an information message is output to see progress on running the batch file,
in current subfolder the folder Converted is created if not already existing,
another FOR loop is executed to process each *.mkv file found in the folder Main of current subfolder.
The loop variable I holds the name of the current *.mkv file with full path. So "%%I" can be used for the input file as current directory does not matter because input file name is with full path.
For the output file the folder Converted in current subfolder is specified and appended is with %%~nxI the file name and the file extension of input file as name for the output file.
This batch code does not require delayed expansion as there is no environment variable used, only the loop variables D and I.
For completeness also your code using a text file containing line by line the folders to process with removing all unnecessary environment variables to make it possible to run the batch file without using the commands setlocal and endlocal.
#echo off
for /F "usebackq tokens=*" %%A in ("f.txt") do (
if exist "%%A\Main\*.mkv" (
echo Processing %%A ...
if not exist "%%A\Converted\*" md "%%A\Converted"
for %%I in ("%%A\Main\*.mkv") do (
ffmpeg.exe -i "%%I" -s 640x480 -map 0 -c:v libx265 "%%A\Converted\%%~nxI"
)
)
)
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.
echo /?
for /?
if /?
md /?
BTW: See this answer and the other answers linked there if you ever want to understand what delayed expansion is and what the commands setlocal and endlocal do not needed here.
#Mofi wrote a great answer, both his codes work flawlessly. This is just a simpler version I am running because the conditions being checked in that program are already met.
#echo off
for /F "tokens=*" %%A in (f.txt) DO (
for %%F in (%%A\Main\*.mkv) DO ffmpeg -i "%%F" -s 640x480 -map 0 -c:v libx265 "%%A\Converted\%%~nxF"
)

Windows batch way to replace all files in subdirectories with singular file (copy, rename all files)

I have a good command over cmd commands, but this may require a variable or a loop which is where I fail in batch commands. Please help if you can!
-- Have about 100 subdirectories each has 1-20 HTML files in it. There are about 100 HTML files in the root directory too.
-- Need to replace all HTML files in the above directories with the same HTML source (copy over existing file and keep the name the same). Basically trying to replace all existing files with a redirect script to a new server for direct bookmarked people. We are running a plain webserver without access to server-side redirects so trying to do this just by renaming the files (locked down corp environment).
Seems pretty simple. I can't get it to work with wildcards by copying the same file over to replace. I only get the first file replaced, but the rest of the files will fail. Any one with any advice?
This should do it from the command prompt. Replace % with %% for use in a batch file.
for /r "c:\base\folder" %a in (*.html) do copy /y "d:\redirect.html" "%a"
Without knowing more precisely how you want to update the file content I suggest the following rough approach.
To re-create your example, I had to create some folders. Run this command to do that:
for /l %i in (1,1,20) do mkdir fold%i
I then used this script to create some example files:
#echo off
set number=0
for /d %%i in (c:\Logs\htmltest\*) do call :makefiles %%i
goto :EOF
:makefiles
set /a number+=1
touch %1\file%number%.txt
echo %number% >%1\file%number%.txt
I then used this script to append the text changed to the file. Not sure if that is what you wanted - probably you need something more sophisticated.
#echo off
set number=0
for /d %%i in (c:\Logs\htmltest\*) do #for %%f in ("%%i\*.txt") do call :changetext %%f
goto :EOF
:changetext
echo changing file contents to ^"changed^" for file: %1
echo changed>>%1

Resources