Batch get csv values ​​and save them as variables for later use

advertisements

I want to extract the values of an file like this:

4564,cde0
7578,Kernel
123465,Performer
INFO,Kernel

I thought putting the data into a csv file would be the easiest option, but if there is an easier way to get the values in variables, I am open for suggestions. I will have way more than four lines...

I want to use the values: From line 1 I need 4564 and cde0 in separate variables. Put them in my script and than continue with line two and so on.

I have found a several threats who deal with columns and by now I have the following code:

for /F "tokens=1-2 delims=," %%a in (test.csv) do (@echo %%a %%b)

But that just shows me the content without the ",".

Is there any way to go through a line and put the two values into two variables?

If so I think the easiest way to go through a csv file would be a loop where I extract the values into variables, use them and continue with the next line, but as I am not very familiar with batch I don't know if that is the best way to do so.

Thank you


At this case, multi-dimensional array will do the trick. Since batch don't have array feature, but we can make it ourself! Just like this:

@echo off
setlocal enabledelayedexpansion

set var1=0

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

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

pause >nul

Let me briefly expalin what's going on here. Multi-dimensional array is an array containing one or more arrays. The most common array looks like array[0], which indicates the 1st element since the element counts from 0.

While multi-dimensional array like array[0][0] indicates the 1st array's 1st array (may sounds confusing). Think of array[0][0] is the line, array[0][0] is the column, so array[1][2] indicates the 2nd line, 3rd column. (*Draw a table and practice)