Solved Splitting single csv to multiple with header.

April 1, 2016 at 11:15:32
Specs: Windows 7
I have a 100 line csv file, with several values per line. I am looking for a way to export each line to its own csv file adding a fixed 2 line header to each. I have used the split command seen elsewhere to create multiple files, but have not found a way to append the header. Also, if possible, can one of the variables be pulled to the file name? Thank you.

Example below.




This is the file I am using:

@echo off
setLocal EnableDelayedExpansion

set limit=1
set file=userlist.csv
set lineCounter=1
set filenameCounter=101

set name=Usertable
set extension=csv
for %%a in (%file%) do (
set "name=%%~na"
set "extension=%%~xa"

for /f "tokens=*" %%a in (%file%) do (
set splitFile=%name%%filenameCounter%%extension%
if %lineCounter% gtr %limit% (
set /a filenameCounter=%filenameCounter% + 1
set lineCounter=1
echo Created %splitFile%.
echo %%a>> %splitFile%

set /a lineCounter=%lineCounter% + 1

See More: Splitting single csv to multiple with header.

Report •

April 1, 2016 at 20:16:48
::====== script starts here ===============
:: sagac.bat 2016-04-02 9:58:04.96
@echo off & setLocal enableDELAYedeXpansioN

for /f "tokens=1-4 delims=," %%a in (my.csv) do (
) > List%%d.csv
goto :eof
::====== script ends here =================


M2 Get custom script or take private lessons

Report •

April 1, 2016 at 20:22:01
✔ Best Answer
This looks very confusing to me. I don't understand the arrangement of the col headings versus the data, and the need for all this excess code to establish basic output. Since the headings are, by def., constant, then it is simple to echo them to the target prior to sending the data to the target. The order of the headings is confusing, esp. since "number" does not seem to be included in the data (only name, age, & color). So your data-columns will not be consistent with the header arrangement and labels. I guess your header is two lines of csv? like:
first     favorite
name age  color

considering this, I would do like:
@echo off & setlocal enabledelayedexpansion
for /f "tokens=1-4 delims=," %%a in (userlist.csv) do (
>list%%d.csv echo first,,favorite
>>list%%d.csv echo name,age,color
>>list%%d echo %%a,%%b,%%c
echo list%%d created
:: --- end script
But I might have it all wrong. This was only my interpretation from the material so far.

@M2: crossed in the mail, ha ha!

message edited by nbrane

Report •
Related Solutions

Ask Question