Ad

Batch Q: How Can I Loop Through All FindStr Results And Present It As A Menu?

- 1 answer

Thanks for you time! This probably won't be a challenge for you.

So I have a list that is a txt file with the format ######.NAME-DATE which corresponds to files. The ##'s are unique identifying numbers, with the date representing different files for the same number. I want to have a batch file ask for the number and find all the files corresponding to that number and present this as a menu so the user can choose which she/he wants to open.

Here is what I have so far:

@echo off   
set /p Input=Enter MRN:

set var=
setlocal enabledelayedexpansion
for /f "tokens=* delims=:" %%a in ('findstr "%Input%" log.txt') do (
    set var=!var!%%a"|"
    SET /A COUNT += 1
)    
set var=!var!
endlocal

PAUSE

Any help would be greatly appreciated! Thank you!

Ad

Answer

@ECHO OFF
SETLOCAL
:: remove variables starting $
FOR  /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="

set /p Input=Enter MRN:

for /f "tokens=1*delims=:" %%a in ('findstr /i /b /n /L "%Input%" q28574900.txt') do (
 set "$%%a=%%b"
)
SET "selection="
for /f "tokens=1,2*delims==:" %%a in ('set $ 2^>nul^|findstr /n /r "^"') do (
 ECHO %%a : %%c
 SET /a selection=%%a
)
IF NOT DEFINED selection ECHO no matches&GOTO :eof
SET "selection="
SET /p "selection=Select which ? "
for /f "tokens=1,2*delims==:" %%a in ('set $ 2^>nul^|findstr /n /r "^"') do (
 IF "%selection%"=="%%a" SET "selection=%%c"&GOTO run
)
ECHO invalid selection
GOTO :eof

:run
ECHO run whatever using %selection%


GOTO :EOF

I used a file named q28574900.txt containing some filename data for my testing. (woud have been better if you'd provided a sample)

First, select names according to input, but with the /b switch (to match at beginning of line) /L for literal-match /i for case-insensitive (in case you want alpha-match too) and /n to provide a unique number: at the start of the line. Having first cleared out all $ variables, set $uniquenumber to the filename found.

Display the menu by running all the values of set $ through a findstr /n /r. The lies would be of the form 3: $3=filename3 so delimit on : and = and show the first and third tokens. UUse selection as a flag (if set, 1 or more files found - can use the fact that if selection is 1 at the end to auto-run if desired)

Then ask for a selection and match the selection made to the list using the same method as used to display the menu. If you find the selection made, set the filename in selection and run the required program, if not, report the problem and finish.

Note that if you enter "12" as input then all files starting 12 will be displayed. If you want to match including the . then append . to %input% in the first findstr.

Ad
source: stackoverflow.com
Ad