从变量获取文件名 [英] Get File name from a variable

查看:71
本文介绍了从变量获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是批处理文件编程的新手,所以如果这很明显,请原谅我.假设我在 TheFileToPass 中存储了一个 c:\ some \ path \ someFile.extension 字符串,并且我正在从同一批处理文件中调用另一个exe,所以我应该只将其传递从 TheFileToPass 中扣除的文件名(即 someFile ).

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"

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

调用external_tool.exe TheFileToPass.GetFileNameWithoutExtension()

call external_tool.exe TheFileToPass.GetFileNameWithoutExtension()

通过在线搜索,我知道%〜nI 可以解决问题,但是如何在 TheFileToPass 变量上使用它呢?我尝试了以下方法,但没有任何效果:

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:

回声%%〜TheFileToPass

echo %%~TheFileToPass

回声%%〜n%TheFileToPass%

echo %%~n%TheFileToPass%

编辑

好吧,我会尽量描述一下.我在批处理文件中定义了几个局部变量":

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=

然后我解析命令行参数,并将其放在声明的变量上方.批处理文件可以具有可变数量的命令行参数,因此值的位置可以根据一些预定义的规则而变化.简而言之,我们无法确定%1,%2,%3(等等)中的哪一个将始终具有文件路径.无论如何,基于预定义的规则,我们将解析命令行参数(使用SHIFT循环技术),并将该信息保留在我们的变量中:someFlag1,someFlag2和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.

现在,someFile包含文件的完整路径,例如:"c:\ some \ path \ file.txt".我们希望调用一个外部exe,并从someFile变量(在本例中为"file")的内容中传递文件名.

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).

那么我们要对仅从全路径获取文件名的"someFile"变量执行什么操作呢?

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

推荐答案

您说您正在使用shift遍历批处理文件的参数以获取文件名.因此,稍后,您将获得

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"

这篇关于从变量获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆