Solved Pull string by line # from text file to var

August 5, 2011 at 13:53:17
Specs: Windows 7
I'm trying to create a batch file to simplify a process in which a filename must be used in a command line tool.


Currently, I'm just using what's below to display available files and have the user manually type them out:

DIR /W /B *.ext
SET /P filename=[Which file do you want to use?]


To greatly simplify this process, I would like to store filenames in a text file (DIR /W /B *ext > dir.txt) and have the user simply input "1", "2", "3", etc, to pull the string from the corresponding line number in the text file into a variable.

Is this even possible?

OR, is there a way to do this without storing anything in a file?


See More: Pull string by line # from text file to var

Report •


#1
August 5, 2011 at 15:38:14
✔ Best Answer
Two versions, one without file and one with:


Without:

@echo off
SetLocal EnableDelayedExpansion
for /f "tokens=1* delims=[]" %%a in ('DIR /B *.ext ^|find /n /v ""') do (
    echo [%%a]%%b
    set list%%a=%%b
    set max=%%a
)

:input
set filenum=
SET /P filenum=[Which file do you want to use?]
if not defined filenum goto input
for /f "tokens=1* delims=0123456789" %%a in ("A0!filenum!") do if not "%%b"=="" goto input
if !filenum! gtr !max! goto input
if !filenum!==0 goto input
set filename=!list%filenum%!

rem cleanup
for /l %%a in (1 1 !max!) do set list%%a=
set max=
set filenum=

echo !filename!
pause


With:

@echo off
SetLocal EnableDelayedExpansion
DIR /B *.ext | find /n /v "" > filelist.txt
for /f "tokens=2 delims=:" %%a in ('find /c /v "" filelist.txt') do set /a max=%%a
type filelist.txt

:input
set filenum=
SET /P filenum=[Which file do you want to use?]
if not defined filenum goto input
for /f "tokens=1* delims=0123456789" %%a in ("A0!filenum!") do if not "%%b"=="" goto input
if !filenum! gtr !max! goto input
if !filenum!==0 goto input

for /f "tokens=1* delims=]" %%a in ('findstr /b "\[!filenum!\]" filelist.txt ') do (
    set filename=%%b
)

echo !filename!
pause


Report •

#2
August 6, 2011 at 13:56:06
Worked perfectly! Thank you :)

Report •
Related Solutions


Ask Question