Reputation: 21
You may call it a duplicate question but the fact is I could not find the solution. May be you can re direct if you do not want to answr.
I have a file name in a variable as A123_101234_3. I want to split the string based on underscore as delimiter and then use the last part "3" of the string for further comparison ( it is actually month number).
Thanks for your help
Upvotes: 1
Views: 11512
Reputation: 57332
for /f "tokens=3 delims=_" %%# in ("A123_101234_3.csv") do set month=%%~n#
echo %month%
Upvotes: 2
Reputation: 70971
Knowing it is the third element and elements are underscore separated, you can use the for /f
tokenizer
set "input=A123_101234_3"
for /f "tokens=3 delims=_" %%a in ("%input%") do set "output=%%a"
Knowing it is the last element in input but not knowing how many elements there are, you can convert the underscore to a space and iterate over the list of elements. This will overwrite the output variable keeping the last element
set "input=A123_101234_3"
for %%a in ("%input:_=" "%") do set "output=%%~a"
If the data includes spaces or other delimiters, you can replace the underscore with a backslash and handle the input as a file reference
set "input=A123_101234_3"
for %%a in ("%input:_=\%") do set "output=%%~nxa"
Upvotes: 6