Reputation: 47
Okay, I am trying to get the name of a folder as a value in batch. The folder looks like this:
John_1
I am trying to only get the first part of the name the John part which is separated with an underscore.
Anyone got any solutions?
Thanks
Upvotes: 1
Views: 121
Reputation: 9266
Like most string processing in batch, the FOR /F
command enables you to do this, with the use of the delims
argument.
for /f "delims=_" %%a in ("john_1") do set "name=%%a"
Now the part you want is in the %name%
variable.
Usually you have the string to parse in a variable and not source, though. To run the above with a variable, you can echo
the variable.
set sz=John_1
for /f "delims=_" %%a in ('echo %sz%') do set "name=%%a"
Finally, if for any reason you want to get the second part of the string, FOR
can allocate another variable to hold it by using the tokens=
argument.
set sz=John_1
for /f "tokens=1,2 delims=_" %%a in ('echo %sz%') do ( set "name=%%a" & set "number=%%b" )
FOR
is one of the most powerful commands in the batch language. Run help for
to see the full list of options available.
Upvotes: 3