A quite simple solution is to use the find
command since this appends a final line-break when needed, so you do not have to particularly take care of that on your own:
@echo off
rem /* Use a flag-style variable that indicates the first file,
rem so we know whether or not we have to apply the header: */
set "FIRST=#"
rem // Write to the output file:
> "Combined.txt" (
rem /* Loop through all input files, with the order is defined by the file system
rem (the used pattern also ensures to does not match the output file): */
for %%I in ("s*.txt") do (
rem // Query the flag-style variable:
if defined FIRST (
rem // This is the first input file, hence return the whole content:
< "%%~I" find /V ""
) else (
rem // This is not the first input file, hence exclude the header:
< "%%~I" find /V "Header"
)
rem // Clear the flag-style variable here:
set "FIRST="
)
)
If the header string (Header
) may occur within other lines but the headline also, try to replace the command line < "%%~I" find /V "Header"
by the one < "%%~I" (set /P ="" & findstr "^")
, although this might cause problems on certain Windows versions as findstr
might hang (refer to the post What are the undocumented features and limitations of the Windows FINDSTR command?).
Here is an approach based on for /F
loops; the difference to your similar approach is that also the first file is handled by a for /F
loop, which lets also the last line be terminated by a line-break in the output:
@echo off
rem /* Use a flag-style variable that indicates the first file,
rem so we know whether or not we have to apply the header: */
set "FIRST=#"
rem // Write to the output file:
> "Combined.txt" (
rem /* Loop through all input files, with the order is defined by the file system
rem (the used pattern also ensures to does not match the output file): */
for %%I in ("s*.txt") do (
rem // Query the flag-style variable:
if defined FIRST (
rem // This is the first input file, hence return the whole content:
for /F "usebackq delims=" %%L in ("%%~I") do (
echo(%%L
)
) else (
rem // This is not the first input file, hence exclude the header:
for /F "usebackq skip=1 delims=" %%L in ("%%~I") do (
echo(%%L
)
)
rem // Clear the flag-style variable here:
set "FIRST="
)
)
Note that a for /F
skips blank lines.