Batchfile looping through CSV file?

Batchfile looping through CSV file?

I'd like a .bat file to loop through the contents of a simple csv text file but my knowledge is limited to simple in-bat loops like 'FOR %%G IN (AA BB CC) DO echo %%G'

I have a text file fruit.txt with two CSV columns of data and n rows, something like

apple,5
orange,3
durian,0

and want to basically grab the first line, parse the fruit-name and number-sold, and print them out.

No clue how to do this. I think its possible, but I havent done .bat in like 30 years?

Answer

Oops figured it out!

@echo off
setlocal enabledelayedexpansion

REM Set the path to your CSV file
set "file=C:\Users\arod\Desktop\fruit.txt"

REM Read the file line by line
for /f "tokens=1,2 delims=," %%A in (%file%) do (
    set "fruit=%%A"
    set "quantity=%%B"
    echo Fruit: !fruit! - Sold: !quantity!
)

endlocal
pause

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles