Home > Software design >  Remove Comma on last value of Loop
Remove Comma on last value of Loop

Time:10-06

I am creating a list using a file with a for loop. Is there a way of not including a comma on the last value of my loop?

Here is the code:

for /F %%a in (test.txt) do (set comma=,& echo %%a !comma!) >> Output.txt

where test.txt contains a list:

ABC 
123 
EG

and i hope to achieve something like this:

ABC,
123,
EG

CodePudding user response:

Just a basic method. test the number of lines, only add a comma if the line number does not match the total number of lines:

@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

CodePudding user response:

What you can do is set the FOR variable to an environmental variable. Then only output that line when the previous line is present. Then output the last line outside of the loop.

@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
  • Related