Page 1 of 1

FOR /F Delimiter Question

Posted: 11 Oct 2011 19:05
by alleypuppy
Hello,

I have a question about delimiters in a FOR /F loop. I'm trying to extract the host name and share name from a previously specified network path (\\server\share).

I can extract the server/host name using the following command:

Code: Select all

SET NTWK=\\computer1\folder1$

FOR /F "TOKENS=1 DELIMS=\" %%a IN ('ECHO %NTWK%') DO SET HOST=%%a
The end result will be HOST=computer1.

I can also extract the share name using the following command:

Code: Select all

SET NTWK=\\computer1\folder1$

FOR /F "TOKENS=2 DELIMS=\" %%a IN ('ECHO %NTWK%') DO SET SHARE=%%a
The end result of this will be SHARE=folder1$.

Now here is where the issue comes in: If the share name specified is, lets say, folder1$\folder2, then the FOR /F loop will only give me folder1 as the result. For example:

Code: Select all

SET NTWK=\\computer1\folder1$\folder2

FOR /F "TOKENS=2,3 DELIMS=\" %%a IN ('ECHO %NTWK%') DO SET HOST=%%a

ECHO %SHARE%
folder1$
I understand why this is happening - it is because of the "\" delimiter. I have tried setting the tokens equal to 3; 2-3; and 2,3; but it still doesn't give me the end result as SHARE=folder1$\folder2. Any ideas?

Thanks in advance! :wink:

Re: FOR /F Delimiter Question

Posted: 11 Oct 2011 20:23
by dbenham
This is easily solved using * representing the remainder of the line, disregarding any delimiters.

Code: Select all

@ECHO OFF
SET NTWK=\\computer1\folder1$\folder2
FOR /F "TOKENS=1,* DELIMS=\" %%a IN ('ECHO %NTWK%') DO SET "HOST=%%a" & set "SHARE=%%b"
ECHO HOST=%HOST%
ECHO SHARE=%SHARE%


Note - If you already have your string in a variable, it is more efficient to use the "string" form of FOR /F instead of 'command':

Code: Select all

FOR /F "TOKENS=1,* DELIMS=\" %%a IN ("%NTWK%") DO SET "HOST=%%a" & set "SHARE=%%b"


Dave Benham

Re: FOR /F Delimiter Question

Posted: 12 Oct 2011 15:32
by alleypuppy
dbenham wrote:This is easily solved using * representing the remainder of the line, disregarding any delimiters.

Code: Select all

@ECHO OFF
SET NTWK=\\computer1\folder1$\folder2
FOR /F "TOKENS=1,* DELIMS=\" %%a IN ('ECHO %NTWK%') DO SET "HOST=%%a" & set "SHARE=%%b"
ECHO HOST=%HOST%
ECHO SHARE=%SHARE%


Note - If you already have your string in a variable, it is more efficient to use the "string" form of FOR /F instead of 'command':

Code: Select all

FOR /F "TOKENS=1,* DELIMS=\" %%a IN ("%NTWK%") DO SET "HOST=%%a" & set "SHARE=%%b"


Dave Benham

Thank you! I totally forgot about the asterisk lol! And thanks for the tip! :)