FOR /F Delimiter Question

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
alleypuppy
Posts: 82
Joined: 24 Apr 2011 19:20

FOR /F Delimiter Question

#1 Post by alleypuppy » 11 Oct 2011 19:05

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:

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: FOR /F Delimiter Question

#2 Post by dbenham » 11 Oct 2011 20:23

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

alleypuppy
Posts: 82
Joined: 24 Apr 2011 19:20

Re: FOR /F Delimiter Question

#3 Post by alleypuppy » 12 Oct 2011 15:32

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! :)

Post Reply