我正在使用帶有 for 回圈的檔案創建串列。有沒有辦法在回圈的最后一個值上不包含逗號?
這是代碼:
for /F %%a in (test.txt) do (set comma=,& echo %%a !comma!) >> Output.txt
其中 test.txt 包含一個串列:
ABC
123
EG
我希望實作這樣的目標:
ABC,
123,
EG
uj5u.com熱心網友回復:
只是一個基本的方法。測驗行數,如果行數與總行數不匹配,則只添加逗號:
@echo off
setlocal enabledelayedexpansion
set "comma=,"
set counter=0
for /F %%i in ('type test.txt ^| find /C /V "^"') do set cnt=%%i
(for /F %%a in (test.txt) do (
set /a counter =1
if !counter! lss %cnt% (
echo %%a%comma%
) else (
echo %%a
)
))> Output.txt
uj5u.com熱心網友回復:
您可以做的是將FOR變數設定為環境變數。然后僅在存在前一行時輸出該行。然后輸出回圈外的最后一行。
@echo off
setLocal enableDELAYedeXpansioN
set "line="
for /f "delims=" %%a in (test.txt) do (
if defined line echo !line!,
set "line=%%a"
) >>Output.txt
(echo %line%)>>Output.txt
uj5u.com熱心網友回復:
這個答案可能更具有學術價值,但我忍不住嘗試使用能夠搜索換行符之外的findstr命令,我打算用它來檢索除最后一行和最后一行之外的所有內容之后。
最棘手的部分是要找到一個方法來解決這個問題,搜索字符.的檔案結尾出人意料地匹配記錄在這篇文章。我希望下面的代碼匹配最后一行,但它失敗了(字串!_LF!!_CR!*!_LF!匹配空行之前的行,因為有兩個連續的換行符,并且字串!_LF!.應該匹配非空行之前的行,不包括最后一行,因為有要么根本沒有換行符,要么后面沒有任何內容,但這失敗了):
rem // Delayed expansion is enabled, the variables `_LF` and `_CR`
rem are set to line-feed and carriage-return characters, resp.:
findstr /V "!_LF!!_CR!*!_LF! !_LF!." "test.txt"
因此,我不得不使用一種方法來解決這個問題,不幸的是不得不使用多個findstr命令,每個命令都自己讀取檔案:
rem /* Test for trailing line-break using `$`, which anchors to carriage-return;
rem due to this, Unix-style text files are not supported by this method: */
> nul findstr /V "$" "test.txt" && (
rem // There is no trailing line-break, so `$` does not match the last line:
findstr "$" "test.txt"
) || (
rem /* There is a trailing line-break, so return all lines that precede two line-breaks
rem with something (except line-breaks since `.` does not match such) in between: */
findstr "!_LF!.*!_CR!!_LF!" "test.txt"
)
這是完整的方法:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_FILE=.\test.txt" & rem // (path to target file)
(set ^"_LF=^
%= blank line =%
^") & rem // (this gathers a line-feed character)
rem // Gather a carriage-return character:
for /F %%Z in ('copy /Z "%ComSpec%" nul') do set "_CR=%%Z"
rem // Iterate through lines of text line by line:
for /F delims^=^ eol^= %%L in ('
rem/ First test for final line-break, then do specific search: ^
^& ^> nul findstr /V "$" "%_FILE%" ^
^&^& ^(findstr "$" "%_FILE%"^) ^
^|^| ^(cmd /V /C findstr "!_LF!.*!_CR!!_LF!" "%_FILE%"^)
') do (
rem /* Here all but the last lines are enumerated, which are then output
rem with a comma `,` appended; note that empty lines are ignored: */
echo(%%L,
)
rem // Here the last line is returned, independent from final line-break:
setlocal EnableDelayedExpansion
findstr /V "$" "!_FILE!" || findstr /V "!_LF!.*!_CR!!_LF!" "!_FILE!"
endlocal
endlocal
exit /B
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312628.html
