Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

importing data from a csv file using Batch file

I am trying to extract data from csv file and displaying it .But my output is not not as desired
What is wrong in my code. My code is

@echo off
setlocal enabledelayedexpansion

set var1=0

for /F "tokens=1* delims=," %%a in (text.csv) do (
    set var2=0
    set var3=0
    set array[!var1!][!var2!]=%%a
    set /a var3=var2+1
    set array[!var1!][!var3!]=%%b
    set /a var3+=1
    set array[!var1!][!var3!]=%%c
    set /a var1+=1
)

echo First column, First element: %array[0][0]%
echo First column, Second element: %array[0][1]%
echo First column, Third element: %array[0][2]%
echo Second column, First element: %array[1][0]%
echo Second column, Second element: %array[1][1]%
echo second column, Third element: %array[0][2]%

pause >nul

The content of Text.Csv file is displayed below

DK joshi,152,uttarakhand,1
amit,154,UP,2
pooja,36,Haryana,3
naveen,565, uttar pradesh,4
suyal,985,uk,5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The displayed output by the code is given below-

First column, First element: DK joshi
First column, Second element: 152,uttarakhand,1
First column, Third element: %c
Second column, First element: amit
Second column, Second element: 154,UP,2
second column, Third element: %c

Required output should be

First column, First element: DK joshi
First column, Second element: 152
First column, Third element:uttarakhand
Second column, First element: amit
Second column, Second element: 154
second column, Third element: UP

>Solution :

If you want to use three separate tokens, you have to explicitly tell the loop that.

"tokens=1* delims=," %%a means "When you split the string, I want you to put the first part in %%a and everything else in %%b, and I want that thing that you split on to be ,."

If you want to use %%a, %%b, and %%c, then you need to either list tokens=1,2,3 or give the range tokens=1-3.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading