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

fledgling
  • 991
  • 4
  • 25
  • 48

4 Answers4

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%
jeb
  • 78,592
  • 17
  • 171
  • 225
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

Mark Leiber
  • 3,118
  • 2
  • 13
  • 22
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-
Stephan
  • 53,940
  • 10
  • 58
  • 91
2

Another way:

set "SERVERNAME=VKR\SQL2012"
set "value=%SERVERNAME:\=" & rem "%"
echo %value%
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • 1
    What kind of sorcery is happening here, please?? – Daniel Luz Apr 19 '16 at 20:59
  • @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](http://stackoverflow.com/questions/36745570/set-a-command-expands-with-a-comma-for-more-than-one-var-only-set-does-not/36748769#36748769). – Aacini Apr 20 '16 at 18:38
  • 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 =/) – Daniel Luz Apr 20 '16 at 21:29
  • @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%` – Aacini Apr 21 '16 at 11:10
  • 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 – Daniel Luz Apr 22 '16 at 01:18
  • @DanielLuz: Well, if you liked this method, you'll get more fun at [this post](http://www.dostips.com/forum/viewtopic.php?f=3&t=6429) – Aacini Apr 22 '16 at 01:36