【问题标题】:Batch files, $ : and ~批处理文件,$ : 和 ~
【发布时间】:2009-04-28 01:32:47
【问题描述】:

我一直在编写一个需要在文件中扩展环境字符串的应用程序。

为此,我可以使用标准的 Windows API 函数 ExpandEnvironmentStrings: http://msdn.microsoft.com/en-us/library/ms724265(VS.85).aspx

不过,我在使用该功能时确实存在一些问题。 第一的: The size of the lpSrc and lpDst buffers is limited to 32K.

下一个:Note that this function does not support all the features that Cmd.exe supports. For example, it does not support %variableName:str1=str2% or %variableName:~offset,length%.

我想实现 cmd.exe 允许的这些额外功能,但我不确定它们到底是什么。 :~offset,length 有点明显......子字符串。但不确定第一个是什么。

有什么想法吗?

比利3

【问题讨论】:

    标签: batch-file environment-variables


    【解决方案1】:

    这是字符串替换。

    基本上,如果 variableName 设置为 "I am three",则 "%variableName:three=four%" 会生成 "I am four"(双引号是为了更好地格式化,它们不构成字符串的一部分)。

    C:\Documents and Settings\Administrator>set x=I am three
    
    C:\Documents and Settings\Administrator>echo %x%
    I am three
    
    C:\Documents and Settings\Administrator>echo %x:three=four%
    I am four
    

    你也可以用空字符串替换(很明显)并从字符串的开头替换(不太明显):

    C:\Documents and Settings\Administrator>echo %x:three=%
    I am 
    
    C:\Documents and Settings\Administrator>echo %x:*am=I am not%
    I am not three
    

    此外,子字符串变体是 Pythonesque,因为负数从字符串的 end 开始工作:

    C:\Documents and Settings\Administrator>echo %x:~,4%
    I am
    
    C:\Documents and Settings\Administrator>echo %x:~-5%
    three
    

    【讨论】:

    • 作为自MSDOS 2 左右以来COMMAND.COM 的幸存者,CMD.EXE 更令人愉快。能够直接从交互式命令提示符测试和演示变量替换之类的东西特别好。在过去的美好时光中,环境变量替换之类的某些事情只在批处理文件中有效,而不是在提示符下。
    猜你喜欢
    • 2014-11-15
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多