Довольно простым решением является использование команды find
, поскольку при необходимости добавляется окончательный перенос строки, поэтому вам не нужно особенно заботиться об этом самостоятельно:
@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="
)
)
Если строка заголовка (Header
) может встречаться в других строках, кроме заголовка, попробуйте заменить командную строку < "%%~I" find /V "Header"
на < "%%~I" (set /P ="" & findstr "^")
, хотя это может вызвать проблемы в некоторых Windows версии как findstr
могут зависать (см. пост Каковы недокументированные особенности и ограничения команды Windows FINDSTR? ).
Вот подход, основанный на подходе на for /F
петлях; отличие от вашего аналогичного подхода заключается в том, что первый файл также обрабатывается for /F
l oop, что позволяет также завершить последнюю строку переводом строки в выводе:
@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="
)
)
Обратите внимание, что for /F
пропускает пустые строки.