1

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

2 Answers 2

6

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"
Sign up to request clarification or add additional context in comments.

Comments

2
for /f "tokens=3 delims=_" %%# in ("A123_101234_3.csv") do set month=%%~n#
echo %month%

2 Comments

The solution is working perfectly fine. But instead of month number it is giving me 3.csv as the file name has the extension of .csv. I added a command, if %month:~-5,1%==3 for comparison but here issue is what if month number has 2 digits. how can i resolve it? How can i just ignore last 4 character from it so that I am left with month number only for comparison? appreciate your help.
@Sharma: In your question you said: "I have a file name in a variable as A123_101234_3". If this is not true, but the file name have a .csv extension this way: "A123_101234_3.csv", then you should modify that information in the original question! Posting additional data in comments is a very bad practice, because you force the readers to read all comments in all answers in order to understand your problem... :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.