0

I have a batch script:

echo on
Set appdir=This is testing for substring : Management\s18vx
ECHO %appdir%

REM get substring i.e, s18vx
Set SubStr = %appdir:~43%
ECHO %SubStr%

cmd /k

After getting the sub string, I am setting it to new variable. On Echo on this variable prints nothing. Not sure what is going wrong here. Basically I want to populate the new variable with extracted string i.e, s18vx in this case.

enter image description here

Gerhard
  • 22,678
  • 7
  • 27
  • 43
MIM
  • 499
  • 3
  • 11
  • 30
  • Either use `ECHO %SubStr %` to match the name you've set for the variable, or use the correct syntax to `Set` the variable in the first instance, i.e. `Set "SubStr=%appdir:~43%"`, followed by `ECHO %SubStr%` as before. As a side note, I'd probably consider using `Set "SubStr=%appdir:*\=%"` instead. – Compo Jan 14 '19 at 13:58
  • @Compo Regarding the side note part. What happens if in his real world scenario the string becomes `Set "appdir=C:\apps\documents\s18vx"` if this string is in fact the case as per his example, then that option is 100% better, but I suspect OP might be using an actual path. :) – Gerhard Jan 14 '19 at 14:26
  • 2
    @Gerhard, I see what you're thinking, and if that were the case, I'd suggest parsing it as a normal file folder path, and using the appropriate modifier, e.g. `%~nxI`. – Compo Jan 14 '19 at 16:23

1 Answers1

6

Give this one a go:

@echo off
set "appdir=This is testing for substring : Management\s18vx"
echo %appdir%

REM get substring i.e, s18vx
Set "SubStr=%appdir:~43%"
echo %SubStr%
pause

The Spaces before and after = is really not wanted it here. This will create a variable name with a trialing space and a value with a leading space, i.e: set variable = value will therefore become %variable % and value.

Also wrap your variables in double quotes to eliminate additional whitespace, especially after the variable string.

For more help on the set command, open cmd.exe and type set /?

Some side notes: Echo is on by default, unless this forms part of a script where echo is turned off earlier and you want to turn it on for some reason, you do not need to switch it on.

Also, I suggest if you want an end result only to turn @echo off because echo on is almost like a debug function, it echos each of the commands you run, where echo off will disable this and display the end result only.

Gerhard
  • 22,678
  • 7
  • 27
  • 43