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
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
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%
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%
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-
Another way:
set "SERVERNAME=VKR\SQL2012"
set "value=%SERVERNAME:\=" & rem "%"
echo %value%