I have a .csv file with a number of rows but I only want the first three rows and none of the rest. How can I use a batch file to export those top 3 rows of my .csv file into another file .csv file? I saw some similar questions with solutions that referenced text files but my attempts to amend the batch file weren't quite as successful. Anyone have any suggestions here?


Using this post from Stack overflow, (named head.bat by the author) it can be amended to do just what you are asking.

head.bat 3 foo.csv

This will take the top n lines from foo.csv and create a file called bar.csv that only contains those 3 lines. You can either feed it the file name and count or simply call this from your batch file. This could be used with the for command and additional variables to process multiple files and output multiple files.

    @echo off

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

call :print_head %1 %2
goto :eof

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

for /f ^"usebackq^ eol^=^

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

goto :eof

echo Usage: head.bat COUNT FILENAME
  • Thanks a million. This worked exactly as I wanted it to. – batchnoober Mar 17 '13 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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