yeniv
yeniv

Reputation: 1639

Win batch scripting: extract substring from string

I want to extract a substring from a string based on the delimiter /. The substring extraction has to be hungry so the I want to get all characters from the string up to the last /. Example:

String: /ab/bcd/casd/adsd/se/23

Substring: /ab/bcd/casd/adsd/se/

P.S.: I have seen other QnAs and they don't answer the specific part where the last delimiter occurrence should be used to extract the substring.

Upvotes: 0

Views: 576

Answers (1)

Magoo
Magoo

Reputation: 80023

@ECHO OFF
SETLOCAL
SET "String=/ab/bcd/casd/adsd/se/23"
FOR /f "delims=" %%a IN ("%string%") DO SET substring=%%~pa
SET "substring=%substring:\=/%"
echo %substring%

GOTO :EOF

You're a little short on specifics. This may work for you assuming the string involved doesn't contain \. Treat the string as a filename, remove the "name+extension" then reverse the / to \ conversion.

Upvotes: 2

Related Questions