【问题标题】:Extracting string after last instance of delimiter in a Batch file在批处理文件中最后一个分隔符实例之后提取字符串
【发布时间】:2013-11-29 01:17:33
【问题描述】:

我正在编写一个由 Java 程序调用的 Windows 批处理文件。许多表示文件目录的不同字符串作为参数传递到批处理文件中。我试图弄清楚如何在“\”的最后一个实例之后提取字符串。比如我有三个目录:

C:\Users\owner\Documents
C:\Users\owner\Videos
C:\Users\owner\Pictures\Trip

我想把它拆分成字符串变成:

Documents
Videos
Trip

你们建议我怎么做?

编辑:这里提出了一个后续问题:For loop in Windows batch file: Error: "The syntax of the command is incorrect"

【问题讨论】:

    标签: string batch-file split delimiter


    【解决方案1】:

    将一个参数分配给“param”变量后,使用:

    for %%a in (%param:\= %) do set lastDir=%%a
    

    只要最后一个目录没有空格,此方法就有效。如果需要,可以修复此细节。所有参数的处理是这样的:

    :nextParam
       set "param=%~1"
       if not defined param goto endParams
       for %%a in (%param:\= %) do set lastDir=%%a
       echo Last dir: %lastDir%
       shift
    goto nextParam
    :endParams
    

    或者,以更简单的方式(没有空格限制):

    :nextParam
       if "%~1" equ "" goto endParams
       echo Last dir: %~N1
       shift
    goto nextParam
    :endParams
    

    【讨论】:

    • 这个答案非常有帮助!这正是我想要的。感谢所有帮助过的人!
    【解决方案2】:

    如果字符串作为参数 1-3 传递。您可以使用 %~n1, %~n2, %~n3 来获取路径中的最后一个文件夹。

    【讨论】:

    • 我认为这是一个好的开始。我忘了提到传入批处理文件的参数数量未知,所以我必须以某种方式让程序确定参数的数量并为每个参数执行此操作。
    • 您可以改为创建一个无限循环,读取“特定(参数)位置的值并移动”,直到该位置的值变为空白。
    猜你喜欢
    • 2014-11-17
    • 2020-09-13
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2014-05-10
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多