Based on Joey's solution, this is only for the safe handling all special characters %&|<>"
and also !^
.
This is only neccessary, if you expect !
in your file data.
In any other case, Joey's code is better and easier to read.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Initialize the variables we are going to use to avoid using stale environment vars
set LIST=
set COUNT=0
rem Iterate over the lines in the text file
rem We need toggling the delayed expansion inside the loop
rem always disabled if using %%l, enabled for using the variables
for /f "delims=" %%l in (list.txt) do (
rem Append the current line to the list, %%l is only safe if delayed expansion is disabled
set "line=%%l"
setlocal EnableDelayedExpansion
rem To use the line variable, delayed expansion has to be enabled
for %%a in ("!LIST!!line!") do (
endlocal
set "LIST=%%~a"
)
set /a COUNT+=1
rem Count how many we got
rem If we have five items already
setlocal EnableDelayedExpansion
if !COUNT! GEQ 5 (
rem Output them and reset the list
echo(!LIST!
endlocal
set "LIST="
set COUNT=0
) ELSE (
endlocal
)
)
setlocal EnableDelayedExpansion
rem Output the remainder if the list does not contain k×5 lines
if defined LIST echo(!LIST!
Why it is so complicated?
The problem is, that %%a (FOR-Loop-Variables) are expanded just before the delayed expansion is executed. You get problems if the content of %%a contains any !
and then you lose also ^
(only if one or more !
exists).
But you need the delayed expansion to show or compare the content of variables inside of the for-loop (forget about call %%var%%).
Expansion with the delayed syntax !variable! is always safe, independent of the content, as it is the last phase of the parser.
But unfortunately enabling/disabling the delayed exp. always creates a new variable context, when leaving this context you lose all changes of the variables.
Therefore I use the inner FOR-Loop to passing from the enabledDelayed-Context back to the disabledDelayed-Context, so the LIST-var contains the correct data.
hope someone understand what I try to explain.
Some more explanations about phases are at how cmd.exe parse scripts