我正在撰寫一個批處理腳本,我需要從 .csv 中決議文本并遇到了障礙:
我有一個 for 回圈設定來從每一行獲取資料(這很好用)但我最終需要一個由多行分隔的值。例如(我將我想被視為單個條目的內容放在括號中作為背景關系):
(data I need,flag_for_which_process_to_run,dontcare,"data I need
data continued
data continued
this could continue for any number of lines",dontcare,dontcare,dontcare,dontcare)
(repeat)
有沒有辦法讓批處理腳本在不破壞 for 回圈的情況下決議它?如果它是有幫助的,資料%%d 是在雙引號包圍。代碼如下,我所指的部分是 for 回圈中的第二部分。
SETLOCAL EnableDelayedExpansion
for /f "tokens=1,2,3,4 delims=," %%a in (sample.csv) do (
REM Skip if %%b is not flag1
if "%%b"=="flag1" (
.
.
.
)
REM Skip if %%b is not otherflag
if "%%b"=="otherflag" (
REM Set the %%a variable
set device=%%a
echo "%%d"> output\tmp\temp.txt
)
)
uj5u.com熱心網友回復:
鑒于前三個標記/值未加引號(因此它們本身不能包含引號或逗號)并且整個 CSV 檔案不包含轉義或退格字符,以下腳本,當 CSV 檔案作為命令列引數,應該提取您感興趣的值(它只是將它們回顯出來):
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_FILE=%~1" & rem // (CSV file; `%~1` is first command line argument)
rem // Get carriage-return character:
for /F %%C in ('copy /Z "%~0" nul') do set "_CR=%%C"
rem // Get line-feed character:
(set ^"_LF=^
%= blank line =%
^")
rem // Get escape and back-space characters:
for /F "tokens=1,2" %%E in ('prompt $E$S$H ^& for %%Z in ^(.^) do rem/') do set "_ESC=%%E" & set "_BS=%%F"
set "CONT="
rem // Read CSV file line by line:
for /F usebackq^ delims^=^ eol^= %%L in ("%_FILE%") do (
rem // Branch for normal lines:
if not defined CONT (
rem // Get relevant tokens/values:
for /F "tokens=1-3* delims=, eol=," %%A in ("%%L") do (
set "DEVICE=%%A" & set "FLAG=%%B" & set "LINE=%%D"
if not "%%D"=="%%~D" (
rem // Fourth token begins with a `"`, hence remove it and enter branch for continued lines then:
for /F delims^=^ eol^= %%E in ("%%D"^") do set "LINE=%%~E"
set "DATA=" & set "CONT=#"
) else (
rem // Fourth token does not begin with a '"', hence it cannot be continued:
for /F "delims=, eol=," %%E in ("%%D") do (
rem // Do something with the data, like echoing:
echo/
echo FLAG=%%B
echo DEVICE=%%A
echo DATA=%%E
)
)
)
) else set "LINE=%%L"
rem // Branch for continued lines:
if defined CONT (
setlocal EnableDelayedExpansion
rem // Temporarily replace escaped (doubled) `"` with back-space character:
set "LINE=!LINE:""=%_BS%!"
rem // Collect continued data with line-breaks replaced by escape characters:
for /F delims^=^"^ eol^=^" %%D in ("!DATA!%_ESC%!LINE!") do endlocal & set "DATA=%%D"
setlocal EnableDelayedExpansion
if not "!LINE!"=="!LINE:"=!^" (
rem /* There is a single `"` (plus a `,`), which is taken as the end of the continued fourth token;
rem hence replacing back line-breaks and (unescaped) `"`: */
set "DATA=!DATA:*%_ESC%=!" & set "DATA=!DATA:%_BS%="!^"
for %%E in ("!_CR!!_LF!") do set "DATA=!DATA:%_ESC%=%%~E!"
rem // Do something with the data, like echoing:
echo/
echo FLAG=!FLAG!
echo DEVICE=!DEVICE!
echo DATA=!DATA!
endlocal
set "CONT="
) else endlocal
)
)
endlocal
exit /B
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380728.html
標籤:批处理文件
下一篇:啟用延遲擴展后如何列印值
