csvbatch-filebatch-processingbatch-choice

Use data from a .csv file as input to choice command in batch file


I have a simple batch to write to C:\Program Files (x86)\Data\ori.csv file the folowing information: division, originator name

@echo off

    
CHOICE /C NS /M  "Please Choose Division:"
echo.
if errorlevel 1 set division=A8-NN
if errorlevel 2 set division=A8-NS


:PROMPT
set /P ori= "Add %division% Originator? [(Y)=yes / (N)=No] "
IF /I "%ori%" NEQ "N" goto add (
) else (
goto exit
)

:add
set /p oriname= "Please Enter %division% Originator Name "
echo Division %division% Originator %oriname% has been Sucessfully added
echo %division%,%oriname% >>C:\%programfiles(x86)%\data\Ori.csv 
echo.

goto prompt

:exit
pause

the output of csv to be e.g.

A8-NN,Chris
A8-NN,Alfredo
A8-NS,Joe
A8-NN,Patrick
A8-NS,Ann
etc

the data of this .csv is gonna change every 2 months for the divisions (new people assigned in each division)

My problem is that i want in a seperate batch file from ori.csv file to read the data and for a specific division use the choice command to choose one originator

As far i have done this:

CHOICE /C NS /M  "Please Choose Division:"
    echo.
    if errorlevel 1 set division=A8-NN
    if errorlevel 2 set division=A8-NS

count=

for /f "tokens=1-20* delims=," %%a in ('type "C:\%programfiles(x86)%\data\Ori.csv"') do (
if %%a== ("%division%)
        set b = %%b
        set "count=!count!+1"
        echo %count% %%b
        )
)

What i tried to do is to the %count% variable store a number identifier and to the %b variable store the originator name. How can I use those two variables as input to a choice command?


Solution

  • You'll need a slightly different approach. After some clarification in the comments.. I would recommended that you move towards set /p here, simply because we never know how many options there will be, you say max 20, but tomorrow suddenly there are 27, then what? So I will rather be safe than sorry :)

    @echo off & set cnt=0
    setlocal enabledelayedexpansion
    for /f "usebackq tokens=1* delims=," %%a in ("%programfiles(x86)%\data\Ori.csv") do (
        if not defined %%a (
           set /a cnt+=1
           set "%%a=%%a"
           set "!cnt!=%%a"
           echo !cnt!. %%a
        )
    )
    set /p "oper=Please choose Division (1 to !cnt!): "
    
    if not %oper% gtr !cnt! (
        set cnt=0
        for /f "usebackq tokens=1-20* delims=," %%a in ("%programfiles(x86)%\data\Ori.csv") do if "%%a" == "!%oper%!" set /a cnt+=1 & echo !cnt! %%b
    )