2

I have a variable defined in a batch file as follows

set "SERVERNAME=VKR\SQL2012"

I need to extract VKR from this. Is there a way I could do this?

I tried this

set "value=%SERVERNAME:*\=%"
echo %value%

which returned SQL2012 but not VKR

1

4 Answers 4

4

You can use FOR /F, when you don't know how the length of the first part.
The delimiter will split the string at the \ character

set "SERVERNAME=VKR\SQL2012"
for /F "tokens=1 delims=\" %%F in ("%SERVERNAME%") do set "pre=%%F"
echo %pre%
Sign up to request clarification or add additional context in comments.

Comments

2

You can do this to take the first three characters (assuming it's a fixed length):

set "SERVERNAME=VKR\SQL2012"
set "value=%SERVERNAME:~0,3%"
echo %value%

See: http://ss64.com/nt/syntax-substring.html

Comments

2

Sadly, there is no %var:string*=%. But there is a better way: Splitting the string:

set "SERVERNAME=VKR\SQL2012"
for /f "tokens=1,2 delims=\" %%a in ("%servername%") do echo -%%a- -%%b-

Comments

2

Another way:

set "SERVERNAME=VKR\SQL2012"
set "value=%SERVERNAME:\=" & rem "%"
echo %value%

6 Comments

What kind of sorcery is happening here, please??
@DanielLuz: You may run this code with echo on to see exactly what is executed. You may see another example of this technique at this answer.
I looked at the other example and I've kinda understood what it did... But HOW does it happens? Is there any documentation about it? The string substituition is acting like a splitter? Why? And how the splitted tokens went to the final "%" sign? Is it something with the "&" command? (Sorry about all these questions, but this really triggered me =/)
@DanielLuz: There is nothing new here: a %variable% expansion is done before the resulting line is parsed for special characters, like &<|>. Try: set "test=echo one & echo two" followed by %test%
Well, that was new to me! Understood what happened and how, just need to practice and test it for a while. Thank you so much, sir! =D
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.