Search code examples
windowsbatch-filecmd

Remove Comma on last value of Loop


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

Solution

  • 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