1

I am new to batch programming. I want to find filename and its extension from a String. I see answers where path is in for variable e.g.

    for /f %%a in ('dir /B') do (
    file_name= %%~nxa
    )

But following code does not work.

    stringvar="c:/folder1/folder2/abc.txt"
    file_name=%%~nxstringvar

I tried many permutation and combination with stringvar and %% and ~nx in expression. But I did not get filename.

Please consider below code to understand the need.

    stringvar="c:/folder1/folder2/abc.txt"
    filename=getFileName(stringvar)

Any answer or suggestion is most welcome. Thankig you in advance

1 Answer 1

2

Special var parameters are only for special vars (%0,%1, etc) and for "FOR" vars, so first you need to call anything passing the variable like an argument, or to do a FOR:

@Echo OFF
SET "stringvar=c:\folder1\folder2\abc.txt"
Call :sub "%stringvar%"
Pause&Exit

:sub
Echo FILENAME: "%~nx1"
GOTO:EOF

EDIT: don't use "/" slashes, you are on Windows, and don't enclose the var like you are doing, see my example.

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

1 Comment

+1, but I prefer to use FOR variables because FOR is significantly faster than CALL: for %%F in ("%stringVar%") do set "fileName=%%~nxF"

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.