Using For loop to find file name

Microsoft Windows vista business - 3 pac...
February 24, 2010 at 13:49:01
Specs: Windows Vista
I am attempting to obtain information from a text file using the FOR /F command from a batch file.

The text file will have one line for example:

Report\network\testing_WINSOCK.TXT:Provider Path: c:\Program Files (x86)\Microsoft Firewall Client 2004\FwcWsp.dll

My goal is to obtain the dll file in a variable. I have been attempting to use the FOR command, but I am unable to determine what DELIMS I should be using. On the left, there will always be the path for testing_WINSOCK.TXT file, then Provider Path, then the path to the file I need to obtain.

I would like to use the backslash as the DELIMS, but I don’t know what the TOKEN will be. Is there a way to find the last token?

This is what I have so far.

FOR /F “TOKENS=* DELIMS=\” %%G IN (‘more testing_WINSOCK.TXT’) DO (Var=~nxG)

Any help is appreciated.


See More: Using For loop to find file name

Report •

February 24, 2010 at 15:24:58
do you mean to handle an indefinite no. of subdirs?
if it's alway the same no. of \, the number you want is 6.
("tokens=6 delims=\")
if it could be more (any number of) levels down, I would suggest using the colon and 4:
for /f "tokens=4 delims=:" %%a in (testing_WINSOCK.txt) do set dll=%%~nxa

(i would recommend not using "MORE" just on principle)

Report •

February 24, 2010 at 23:46:17
If the file name you want is always 'at the end' try this:


@echo off & setLocal EnableDELAYedeXpansion

set /p var=<myfile

for /f "tokens=* delims=" %%a in ("!var!") do (
  set S=%%a
  set S=!S:\= !
  call :sub1 !S!
echo !S!

goto :eof

  if '%2' neq '' (
    goto :sub1
set S=%1

goto :eof

Helping others achieve escape felicity


Report •

February 25, 2010 at 03:45:13
> Is there a way to find the last token?

Good question. As M2 shows, I think there is not, and you should do the (programmer) obvious : go through all, and remember the last.

You COULD of course, try to get the number of tokens (by means of whatever you need to, if that be a FOR /F so be it), and THEN run another FOR /F to tell to look for token number whatever. But that sort of defeats the whole purpose, as you need to add more code than you wish to.

Report •

Related Solutions

February 25, 2010 at 15:46:06
Thank you M2!!! This works!!!

Report •

February 27, 2010 at 04:48:56
In Unix/Linux, the token-thing can be handled by AWK, and there is a syntax foreseen to tell him to take the last token of the set, no matter what the number of tokens are ... or the second to last, etc.

So ... going from there (you need awk.exe for this to work) :

D:\Temp>echo one two three four five six | awk "{ print $(NF-2) }"

D:\Temp>echo one two three four five six | awk "{ print $NF }"


Report •

Ask Question