How to a batch file overwrite contents of output each time

batch filecommand linecsvredirection

I have this batch file below, which is a simple emulation of Unix’s head command – it will read the first COUNT rows from the input .csv file (named as a command-line parameter). However, unlike the Unix command, it writes to a hard-coded output file. The only issue now is that this batch file will be called several times to create this output file and will keep appending the results to the output file. I can't change the >> to > since this is a for loop and will just keep overwriting a single line into my output file, which is incorrect. Does anyone have any ideas on how to overwrite the output .csv file each time the batch file is run?

@echo off

if [%1] == [] goto usage
if [%2] == [] goto usage

call :print_head %1 %2
goto :eof

REM
REM print_head
REM Prints the first non-blank %1 lines in the file %2.
REM
:print_head
setlocal EnableDelayedExpansion
set /a counter=0

for /f ^"usebackq^ eol^=^

^ delims^=^" %%a in (%2) do (
        if "!counter!"=="%1" goto :eof
        @echo>>trimmed.csv %%a
        set /a counter+=1
)

goto :eof

:usage
echo Usage: head.bat COUNT FILENAME

Best Answer

Rather than deleting the file, I would personally prefer to overwrite the file with 'nothing':

type NUL>trimmed.csv

Put it somewhere above the loop.

This creates a blank file, or overwrites an existing file with an empty file, with the name trimmed.csv. Since it is overwriting, and not deleting and recreating, it should keep the original file creation date.

Related Question