First off, you're setting HeaderString to the name of the file, not the header string. It's difficult to trivially change your approach to get you what you want here.
Also you're trying to use the values of HeaderString
and HeaderString0
in the IF-block where they're set. That's not going to work without delayed expansion, but that doesn't mean that you need delayed expansion; it just means you need to exit the IF block before you can use the values of those variables.
You can set values in an IF-block, then close the IF block, and then rely on them in a second IF-block, which gives you a cookie-cutter pattern for solving that issue.
That's still not going to help you here though because the approach is fundamentally flawed (no easy way to modify just the first line in this context).
A simpler approach would be to:
- get the header line
- do your underscores-for-spaces replacement of the header line
- add the modified header line to your output file
- add all the other content to your output file
With caveats mentioned in the link, this trick will efficiently get the first line (the header line) of one of the csv files into a variable.
Then it's trivial to do our spaces-for-underscores replacement.
Then just append the contents of the rest of the files.
@ECHO OFF
set Outputfolder=c:\Test
REM Get the header string out of one of the files
for %%I in (%outputFolder%\*_stats.csv) do set /p HeaderString=< %%I
REM replace the spaces in that header string with underscores
SET HeaderString=%HeaderString: =_%
REM write that header as the first line of the output file
echo.%HeaderString%>%outputFolder%\all_stats_merged.csv
REM append the non-header lines from all the files
>>%outputFolder%\all_stats_merged.csv (
for %%I in (%outputFolder%\*_stats.csv) do more +1 "%%I"
)
I tested this on Windows 7 and 8.1