@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the directories and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
SET "filename1=%sourcedir%\q72682391.txt"
SET "header="
FOR /f "usebackqdelims=" %%b IN ("%filename1%") DO (
IF DEFINED header (
FOR /f "tokens=1,2,*delims=," %%u IN ("%%b") DO (
FOR /f "tokens=*" %%e IN ("%%v") DO (
MD "%destdir%\%%u" 2>nul
(
ECHO !header!
FOR /f "tokens=*" %%y IN ("%%w") DO ECHO %%y
)>"%destdir%\%%u\%%e.html
)
)
) ELSE SET "header=%%b"
)
GOTO :EOF
Always verify against a test directory before applying to real data.
Outer loop: reads each line of file into %%b. As header is initialised to nothing, on reading the first line, header is not defined, so it is set by the else clause of the if statement to the header line. For every other line, header will be defined, so processing continues:
Next inner loop: %%u is set to the first token (name), %%v to the second (filename) and %%w to the remainder of the line (html).
Next loop: "tokens=*" will strip leading spaces from the string %%v, which includes the space after the comma-delimiter from the previous forso%%e` will contain the filename without the leading space.
Create the destination (name) directory from %%u. The 2>nul suppresses the error reports (like directory already exists)
Enclosing a sequence of lines in parentheses enables us to redirect all of the echoed output to a new file using > rather than having to create using a > and then append using >>.
So, output the contents of header using delayedexpansion syntax Stephan's DELAYEDEXPANSION link
then use the tokens=* mechanism again to output the contents of %%w with the leading spaces suppressed.
Personally, I can't see the point of including the header in the file generated, but that's what you appear to have expected to do with your original code. If you don't want it, simply remove that line.