我试图先将data_set_path
分割为,
,而不是在旁边循环中,我应该能够按->
分割字符串。请帮助我。
set "data_set_path=v1->E:\test1,v2->E:\test2,v3->E:\test3,v4->E:\test4"
答案 0 :(得分:3)
试试这个:
@echo off&setlocal
set "data_set_path=v1->E:\test1,v2->E:\test2,v3->E:\test3,v4->E:\test4"
REM first split by commas
for /f "tokens=1-4 delims=," %%i in ("%data_set_path%") do set "pc1=%%i"& set "pc2=%%j"& set "pc3=%%k"&set "pc4=%%l"
<nul set/p"=1st split: %pc1% %pc2% %pc2% %pc4%"&echo(
REM second split by "->"
for /f "tokens=1-4 delims=->" %%i in ("%data_set_path%") do set "pp1=%%i"& set "pp2=%%j"& set "pp3=%%k"&set "pp4=%%l"
echo 2nd split: %pp1% %pp2% %pp2% %pp4%
REM third split by "->"
for /f "tokens=1,2 delims=->" %%a in ("%pc1%") do set "pc11=%%a"&set "pc12=%%b"
for /f "tokens=1,2 delims=->" %%a in ("%pc2%") do set "pc21=%%a"&set "pc22=%%b"
for /f "tokens=1,2 delims=->" %%a in ("%pc3%") do set "pc31=%%a"&set "pc32=%%b"
for /f "tokens=1,2 delims=->" %%a in ("%pc4%") do set "pc41=%%a"&set "pc42=%%b"
echo 3nd split: %pc11% %pc12% %pc21% %pc22% %pc31% %pc32% %pc41% %pc42%
..输出为:
1st split: v1->E:\test1 v2->E:\test2 v2->E:\test2 v4->E:\test4 2nd split: v1 E:\test1,v2 E:\test1,v2 E:\test3,v4 3nd split: v1 E:\test1 v2 E:\test2 v3 E:\test3 v4 E:\test4
答案 1 :(得分:2)
使用变量扩展搜索和替换将分隔符转换为换行符。 FOR / F在换行符处迭代。
@echo off
setlocal enableDelayedExpansion
:: Define LF to contain a line feed (0x0A)
set LF=^
:: Above 2 empty lines are critical - DO NOT REMOVE
set "data_set_path=v1->E:\test1,v2->E:\test2,v3->E:\test3,v4->E:\test4"
for %%L in ("!LF!") do (
for /f "delims=" %%A in ("!data_set_path:,=%%~L!") do (
set "split1=%%A"
set "split2a="
set "split2b="
for /f "delims=" %%B in ("!split1:->=%%~L!") do (
if not defined split2a (set "split2a=%%B") else set "split2b=%%B"
)
echo name=!split2a! value=!split2b!
)
)
- 输出 -
name=v1 value=E:\test1
name=v2 value=E:\test2
name=v3 value=E:\test3
name=v4 value=E:\test4
如果由于FOR / F EOL功能,名称或值以;
开头,则上述代码将失败。
如果!
出现在内容中的任何位置,由于在展开FOR变量时延迟展开处于活动状态,代码也会失败。
如果需要,这两个问题都可以解决。