0

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?

1 Answer 1

1

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
1
  • Thanks a million. This worked exactly as I wanted it to. Mar 17, 2013 at 13:47

You must log in to answer this question.

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