我有一個 txt 檔案,輸入為 -
First Line data here ...
Second, line data ; here
Third. line data here ..,
我有以下 bat 腳本代碼來逐行讀取 txt 檔案,并在 tmp 變數中具有值,理想情況下應該如下所示 -
{ "s1":"First Line data here ...","s2":"Second, line data ; here","s3":"Third. line data here ..,"}
沒有給我預期輸出的 bat 腳本代碼看起來像 -
@echo off
set /a count=1
set tmp=
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ data.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
echo(!var!
call :processline !var!
ENDLOCAL
)
pause
goto :END
:processline
set txt="%*"
set inp="s%count%"
IF "!tmp!" EQU "" (
echo if called
set tmp=%inp%:%txt%
) ELSE (
echo else called
set tmp=%tmp%,%inp%:%txt%
)
set /a count =1
exit /b 0
:END
echo end called
echo -------
echo %tmp%}
pause
通過一些除錯,我注意到“set tmp=%inp%:%txt%”行實際上沒有在全域范圍內設定并且始終保持為空,如何修改此代碼以在 tmp 中實作所需的 json 外觀輸出?
uj5u.com熱心網友回復:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory & filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q71959582.txt"
SET "json="
FOR /F "usebackq tokens=1*delims=:" %%b in (`findstr /n . "%filename1%"`) do SET "json=!json!"s%%b":"%%c","
SET "json={ %json:~0,-1%}"
SET json
findstr只需在檔案的每一行前加上serial:.
決議結果for /f行,將序列號放入 in%%b并將行的其余部分放在:in之后%%c。
簡單地set附加"s<serialnumber>":"<line contents>",到現有值json
然后所需要的就是將前綴和后綴大括號添加到構建的json值中,所有這些都禁止終端,
您的代碼不起作用的原因(我沒有嘗試過,所以這是理論)是回圈中的setlocal/endlocal括號for建立了環境的本地副本,對其進行操作,然后在endlocal執行時恢復原始值。
由于你setlocal enabledelayedexpansion在代碼的開頭執行了 a delayedexpansion,所以它是打開的,所以你不需要再次打開它。如果您只是從回圈中洗掉setlocaland命令,您的代碼可能會在沒有消失的修改值的情況下作業。endlocalfor
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/461763.html
