Rolwin Crasta
Rolwin Crasta

Reputation: 4339

How to generate a comma separated string using for loop with batch script / powershell in a single line

I have a text file with id's separated by new line

I want this text file to be comma separated using Batch script

Refer my code below, this code generates Comma seperated string but still with new line. I want the comma seperated string in single line

@echo on & setlocal ENABLEDELAYEDEXPANSION 
for /f "tokens=* delims=" %%a in (input.txt) do (
set /a N+=1
echo ^%%a^,>>output.txt
)

input.txt is

1
2
3
4
5

Output.txt should be 1,2,3,4,5

Upvotes: 0

Views: 487

Answers (2)

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "first=1"
    (for /f "delims=" %%a in (input.txt) do (
        if not defined first ( set /p"=,%%a" ) else ( set /p"=%%a" & set "first=" )
    )) <nul >output.txt 

Upvotes: 1

lahell
lahell

Reputation: 66

This is easier with PowerShell:

(Get-Content input.txt) -join ',' | Out-File output.txt

Upvotes: 2

Related Questions