2

I have a 100 line csv file, with 5 values per line. I am looking for a way to export each line to its own csv file adding a 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.

Orig

Jack,7,blue,001   
Jane,6,red,002   
Mike,4,orange,003

result

List001.csv   
first,number,favorite   
Name,age,color   
Jack,7,blue   

...

List002.csv   
first,number,favorite   
Name,age,color   
Jane,6,red   

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
)
2
  • this would be easier with PowerShell or VBScript
    – Keltari
    Commented Apr 1, 2016 at 17:49
  • @Keltari Why? It's trivial in a batch file. See my answer.
    – DavidPostill
    Commented Apr 1, 2016 at 18:42

1 Answer 1

2

I am looking for a way to export each line to its own csv file

adding a 2 line header to each.

Your batch file is over complicated. There is no need to split the file name or use a counter variable.

Use the following batch file (example.cmd):

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-4 delims=," %%i in ('type userlist.csv') do (
  echo first,number,favorite>>List%%l.csv
  echo Name,age,color>>List%%l.csv
  echo %%i,%%j,%%k>>List%%l.csv
  )
endlocal

Example usage:

F:\test>type userlist.csv
Jack,7,blue,001
Jane,6,red,002
Mike,4,orange,003

F:\test>example

F:\test>type List001.csv
first,number,favorite
Name,age,color
Jack,7,blue

F:\test>type List002.csv
first,number,favorite
Name,age,color
Jane,6,red

F:\test>type List003.csv
first,number,favorite
Name,age,color
Mike,4,orange

F:\test>

Further Reading

2
  • Thank you all. I was over thinking the issue and my train of thought got derailed.
    – sagac
    Commented Apr 2, 2016 at 22:46
  • Do you need more help? If this answer was helpful to you and answered your question, please don't forget to accept that answer.
    – DavidPostill
    Commented Apr 2, 2016 at 23:01

You must log in to answer this question.

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