Try this (adapt file names and paths accordingly):
for %%F in ("C:\...\*.txt") do (
> "%%~F.tmp" type "Header.txt"
>> "%%~F.tmp" type "%%~F"
move /Y "%%~F.tmp" "%%~F"
)
This combines the content of Header.txt
and the processed text file in a temporary file (for instance, the text file is Body.txt
, so the temporary file is Body.txt.tmp
), then it moves the temproary file over the original text file, hence it gets replaced. Note that the heading in the file Header.txt
must be terminated with a line-break; otherwise, the heading and the first line of the text file are combined into a single line of text.
In order to check the files whether the already have been inserted the header to, you could redirect their first lines into a variable and compare them with the first line of the header file, like this:
< "Header.txt" set /P HEAD=""
for %%F in ("C:\...\*.txt") do (
< "%%~F" set /P LINE=""
setlocal EnableDelayedExpansion
if not "!LINE!"=="!HEAD!" (
endlocal
> "%%~F.tmp" type "Header.txt"
>> "%%~F.tmp" type "%%~F"
move /Y "%%~F.tmp" "%%~F"
) else endlocal
)
Every single file is checked individually here. For this you need delayed expansion as you are writing to and reading from the same variable within a block of code, that is the for
loop.