Search .csv from within a batch file

batchcsvscriptvbscript

I am looking to create a batch file that will search a .csv for a specific number, and then use the 2nd value in the csv as the input back into the batch file.

Example:

csv name= IP.csv

.csv example

Store,IP
1000,192.168.1.1
2000,192.168.1.2
3000,192.168.1.3
4000,192.168.1.4
5000,192.168.1.5

Batch example

Set /p Store=Enter the Store number:

**Search the .csv for the store number, then reply with the IP address.**

I know this is extremely vague, but any guidance would be greatly appreciated.

Thank you!

Best Answer

Very easily done with batch.

@echo off
setlocal
set /p "store=Enter the store number: "
for /f "tokens=2 delims=," %%A in ('findstr /r "^%store%," "ip.csv"') do echo %%A

The problem could become significantly more complicated for batch if the layout of your csv changes. For example, commas in column values creates issues that require more code to solve.

I've written a hybrid JScript/batch utility called REPL.BAT that could also make short work of this problem. It performs a regex search and replace on stdin and writes the result to stdout. It is pure script that runs on any Windows machine from XP onward - no exe download required. REPL.BAT is available here.. Full documentation is embedded within the script.

REPL.BAT has loads of options, including one that only writes out lines that are altered, making it ideal for this problem. Assuming REPL.BAT is in your current directory, or better yet, somewhere in your PATH:

@echo off
setlocal
set /p "store=Enter the store number: "
type ip.csv|repl "^%store%,(.*)" $1 a

REPL.BAT eliminates many complexities of working with text files in batch. But dealing with commas within csv column values is still tricky.