Bhavneet Singh Bajwa
Bhavneet Singh Bajwa

Reputation: 410

Get File name from a variable

i am totally new to batch file programming so please forgive me if this is plain obvious. Say i have a c:\some\path\someFile.extension string stored in TheFileToPass and i am invoking another exe from the same batch file such that i should only pass it the File name deducted from TheFileToPass (i.e, someFile).

A pseudo code of what i am trying to do:

string TheFileToPass = "c:\some\path\someFile.extension"

call external_tool.exe TheFileToPass.GetFileNameWithoutExtension()

By searching online i came to know that %~nI can resolve the problem but how can i use it on the TheFileToPass variable? i have tried the following but nothing works:

echo %%~TheFileToPass

echo %%~n%TheFileToPass%

EDIT

Okay, i'll try to be more descriptive. i have a couple of "local variables" defined in our batch file:

set someFlag1=
set someFlag2=
set someFile=

Then i parse command line arguments and put them inside above declared variables. The batch file can have variable number of command line arguments so the position of values can vary based upon some predefined rules. In nutshell, we cannot be certain that %1, %2, %3 (etc.) which one will always have the filepath. Anyway, based upon predefined rules, we parse the command line arguments (using SHIFT loop technique) and keep that information in our variables: someFlag1, someFlag2 and someFile.

Now, someFile contains fullpath for the file, e.g.: "c:\some\path\file.txt". And we wish to invoke an external exe and pass it the file name from the contents of someFile variable ("file", in this case).

So what operation do we operate on the "someFile" variable that we only get the filename from the fullpath?

Upvotes: 1

Views: 403

Answers (3)

MC ND
MC ND

Reputation: 70923

You say you are iterating through the parameters of batch file using shift to get the file name. So in some moment, you will have something as

set "someFile=%~1"

Then, all you need to add is the extraction of filename to later use it

set "onlyFileName=%~n1"

Upvotes: 1

npocmaka
npocmaka

Reputation: 57252

for %f in ("%TheFileToPass %") do call external_tool.exe %~nf.GetFileNameWithoutExtension()

Upvotes: 0

David Candy
David Candy

Reputation: 743

It depends on how you are passing the file to the batch file.

You either pass on command line and use %~dpn1 (you'll want the path) or if hard coded pass to a function in the bat and use the same %~dpn1.

Type

call /?
set /?

Upvotes: 0

Related Questions