我有一个多行CSV格式,如下所示:
A/B//D
E//G/H
我正在尝试使用这些a,b,c(在这种情况下为空白)和d作为参数输入。我今天的代码是跳过C并将D分配到第三位置。
FOR /F " tokens=1,2,3,4 delims=/" %%i IN (MYCSV.txt"') DO tabcmd get "MyView.png?Filter1=%%A&Filter2=%%B&Filter3=%%C&Filter4=%%D" -f "Outputfile.png"
预期输出:
Mview.png?Filter1 = A&Filter2 = B&Filter3 =&Filter4 = D
我得到的是: Mview.png?Filter1 = A&Filter2 = B&Filter3 = D&Filter4 =
任何帮助将不胜感激。谢谢。
答案 0 :(得分:1)
您可以将powershell用作具有Import-Csv
cmdlet的批处理工具。
它需要临时分配标题,可以在保存时将其删除。
您选择的定界符将在输出的csv上使用双引号引起来的字段。
powershell -Nop -C "(Import-Csv '.\mycsv.txt' -Delim '/' -Header (1..4))|ConvertTo-Csv -NoType|Select -Skip 1|Set-Content '.\my.csv'"
示例输出:
> type my.csv
"A","B","","D"
"E","","G","H"
答案 1 :(得分:0)
for /F
将相邻的定界符组合为一个,用于解析文本。但是,您可以阅读整行,临时插入一个非定界符以拆分为标记,然后再将其删除,例如:
rem // Read whole lines:
for /F "usebackq delims=" %%A in ("MyCSV.txt") do (
rem // Store current line:
set "LINE=%%A"
rem // Toggle delayed expansion to avoid trouble with `!`:
setlocal EnableDelayedExpansion
rem /* Prepend `_` to line string and replace every `/` by `/_`, hence every `/`-delimited
rem item becomes preceded by `_`, hence no more adjacent delimiters `/` can occur: */
for /F "tokens=1-4 delims=/" %%a in ("_!LINE:/=/_!") do (
endlocal
rem // Get items preceded with `_`:
set "ITEM1=%%a"
set "ITEM2=%%b"
set "ITEM3=%%c"
set "ITEM4=%%d"
setlocal EnableDelayedExpansion
rem // Return rebuild line string with delimiters `,` and preceding `_` removed:
echo(!ITEM1:~1!,!ITEM2:~1!,!ITEM3:~1!,!ITEM4:~1!
)
endlocal
)
当然,只需替换定界符,您就可以这样做:
rem // Read whole lines:
for /F "usebackq delims=" %%A in ("MyCSV.txt") do (
rem // Store current line:
set "LINE=%%A"
rem // Toggle delayed expansion to avoid trouble with `!`:
setlocal EnableDelayedExpansion
rem // Return new line string with delimiters replaced:
echo(!ITEM:/=,!
endlocal
)