Reputation: 1051
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
Upvotes: 2
Views: 15952
Reputation: 67216
Another way:
set "SERVERNAME=VKR\SQL2012"
set "value=%SERVERNAME:\=" & rem "%"
echo %value%
Upvotes: 2
Reputation: 56180
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-
Upvotes: 2
Reputation: 3138
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
Upvotes: 2
Reputation: 82247
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%
Upvotes: 4