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

3
  • 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. Commented Jan 14, 2019 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. :) Commented Jan 14, 2019 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. Commented Jan 14, 2019 at 16:23

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Plus one for the "spacing in =" comment. Was causing me all sorts of trouble.
Thanks, @Jacques, I edited to make it a little clearer as well. (fellow South African)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.