Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 1 down vote accepted

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
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>>bar.csv %%a
        set /a counter+=1
)

goto :eof

:usage
echo Usage: head.bat COUNT FILENAME
share|improve this answer
    
Thanks a million. This worked exactly as I wanted it to. – batchnoober Mar 17 '13 at 13:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .