Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Basically I have this batch file below, which will return the first x rows from the input .csv file parameter. However, 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? Thanks.

@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
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
    
This is good. I actually thought about deleting it but this is a nicer option. –  batchnoober Mar 22 '13 at 18:59
add comment

Perhaps just delete it at the start of the batch (or at the top of the :print_head section)?

Something like del trimmed.csv /Q.

That way it's deleted on the next run, but still gets created and appended to while it's running the loop.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.