【问题标题】:remove specific character from a string with batch script使用批处理脚本从字符串中删除特定字符
【发布时间】:2013-06-03 10:40:48
【问题描述】:

我只想将特定字符删除到字符串中,并且只删除一次。例如,如果我有这个文件:

"1234 + test.txt"

我想删除“+”字符。我的问题是我不知道文件名中有多少个“+”;顺便说一句,我只想删除第一个:

"1234 ++ test + hello + world.txt"

需要:

"1234 + test + hello + world.txt"

我需要使用 bat 脚本来执行此操作。我在正确使用“token,delims”参数时遇到了一些问题......

编辑:我对 Edoro 的解决方案有疑问。如果文件名是"++plus--.txt",%left% 是"plus--.txt",%right% 是+plus--.txt

【问题讨论】:

    标签: string batch-file wildcard


    【解决方案1】:

    纯批次

    @echo off &setlocal
    set "string=1234 ++ test + hello + world.txt"
    
    for /f "delims=+" %%i in ("%string%") do set "left=%%i"
    set "right=%string:*+=%"
    set "new=%left%%right%"
    echo %new%
    

    ..输出为:

    1234 + test + hello + world.txt
    

    【讨论】:

    • 如果我也想修剪“-”,我可以使用“delims=+ -”之类的东西还是需要使用引号?
    • for 循环中,您可以使用多个分隔符,但不能在字符串操作中使用set "right=%string:*+=%"
    • 抱歉,您不能对完全不同的正则表达式使用相同的代码。在这种情况下,new 字符串计算为set "new=%string:++=+%"。这适用于所有类似情况。
    • 这似乎不是解决方案,因为如果文件名是“+test.txt”,最终结果将是“test.txt”
    • 如果你有+test.txt 并使用set "new=%string:++=+%",你会得到+test.txt,正如预期的那样。
    【解决方案2】:

    通过 sed 脚本:

    echo "1234 + test + hello + world.txt" | sed 's/+//'
    

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 2014-02-15
      相关资源
      最近更新 更多