用特殊字符拆分字符串' *'在批处理文件中

时间:2015-11-27 16:21:22

标签: string batch-file split

我需要在*之后删除子字符串。使用批处理文件

Example : 
The value of string is : TEST_SINISTRE*.csv

rem My code : 
SET mystring="TEST_SINISTRE*.csv"

rem Do the split
SET ext_test=%mystring:*.="& rem %"
SET ext_test=%ext_test%

rem what i get
echo %ext_test% ===> "& rem csv"

rem What i want to see
===> TEST_SINISTRE

你能帮帮我吗: - )

2 个答案:

答案 0 :(得分:1)

当且仅当*.模式只能在字符串中出现一次,并且*.之后的部分未包含在*.之前的部分中时,以下内容可能是使用:

rem this is the original string containing one `*.`:
set "STRING=TEST_SINISTRE*.csv"

rem now get everything after `*.`:
rem   (if `*` is the first character in substring substitution, it means everything up to
rem   and including the search string is to be replaced, by nothing here in this case)
set "SUBSTR=%STRING:**.=%"
rem get everything before `*.`, including the `*`:
setlocal EnableDelayedExpansion
set "SUBSTL=!STRING:.%SUBSTR%=!"
rem truncate the `*` from the string:
endlocal & set "SUBSTL=%SUBSTL:~,-1%"

由于使用了变量扩展的替换语法,因此这是以不区分大小写的方式完成的。

为了使其更安全,您可以临时附加原始字符串中可能永远不会发生的内容,然后将其删除。要完成此操作,请使用以下内容替换set / setlocal块之间的endlocal命令行(例如,使用附录###):

set "STRING=!STRING!###"
set "SUBSTL=!STRING:.%SUBSTR%###=!"

答案 1 :(得分:0)

*字符是批处理变量子字符串替换中的通配符。当您在内联替换中执行*.=something时,您实际上是在说“替换所有内容并包括点”。您应该使用for /F循环,以便将星号指定为分隔符。

set "str=TEST_SINISTRE*.csv"
for /f "tokens=1* delims=*" %%I in ("%str%") do set "ext_test=%%I%%J"

echo %ext_test%

我不确定你的最终目标是什么,但这是一个可能的替代品。您实际上可以创建一个名为TEST_SINISTRE.csv的文件,然后将文件名作为通配符匹配捕获到变量中。

set "str=TEST_SINISTRE*.csv"
type NUL > TEST_SINSTRE.CSV

for %%I in (%str%) do set "ext_test=%%I"

echo %ext_test%

我确信这并不是你想到的,但它确实证明了如果要进行文件名匹配,也许你不需要去掉星号。

相关问题