How to Convert a Multi-Line File to a Single Comma-Separated Line in Batch Script
Automation scripts often require list inputs in a specific comma-separated format. For example, if you have a file with a list of 50 server names (one per line), and a management tool requires them as a single string like server1,server2,server3, you need to flatten the file. Turning a multi-line vertical list into a single horizontal line is a common data transformation task.
In this guide, we will demonstrate how to concatenate lines into a single comma-separated string using a for /f loop.
The Strategy: The Concatenation Loop
- Initialize an empty variable (e.g.,
set "csv="). - Read the file line-by-line.
- For each line, append a comma and the text to the
csvvariable. - The conditional check ensures no leading comma appears on the first entry.
Implementation Script
@echo off
setlocal disabledelayedexpansion
set "source=Servers.txt"
set "output=flattened.txt"
set "separator=,"
:: Verify source file exists
if not exist "%source%" (
echo [ERROR] Source file "%source%" not found.
pause
exit /b 1
)
echo Converting lines in "%source%" to a comma-separated string...
set "csv="
for /f "usebackq delims=" %%A in ("%source%") do (
set "line=%%A"
setlocal enabledelayedexpansion
:: Logic to preserve 'csv' across endlocal
if "!csv!" equ "" (
set "temp_csv=!line!"
) else (
set "temp_csv=!csv!!separator!!line!"
)
:: Pass the variable out of the setlocal scope
for /f "delims=" %%B in ("!temp_csv!") do (
endlocal
set "csv=%%B"
)
)
:: Output the result
setlocal enabledelayedexpansion
if not defined csv (
echo [WARNING] No lines found in "%source%". Output file will be empty.
type nul > "%output%"
) else (
echo(!csv!> "%output%"
echo.
echo Result: !csv!
)
endlocal
pause
exit /b 0
Batch variables are limited to 8,191 characters. If your file contains many lines or long lines, the concatenated string will be silently truncated once it exceeds this limit, producing corrupted output with no error message. For files where the flattened result may approach or exceed this limit, use the PowerShell method (Method 2).
The script uses the delayed expansion toggle pattern: each line is set with delayed expansion disabled (set "line=%%A") to preserve literal ! characters in the file content. The concatenation is then performed with delayed expansion enabled (set "csv=!csv!%separator%!line!") to safely handle &, |, >, <, and other special characters in the line values.
Method 2: The PowerShell Bridge (Recommended for Large Files)
For large files, Batch string concatenation grows progressively slower as the variable gets larger and is subject to the 8,191-character limit. PowerShell can join an entire array into a single string without these constraints.
Implementation Script
@echo off
setlocal
set "source=input.txt"
set "output=output.txt"
set "separator=,"
:: Verify source file exists
if not exist "%source%" (
echo [ERROR] Source file "%source%" not found.
pause
exit /b 1
)
echo Converting lines in "%source%" to a comma-separated string...
:: Use $env: to safely pass variables from Batch to PowerShell
:: [System.IO.File]::WriteAllText ensures UTF8 without BOM (standard in modern envs)
powershell -NoProfile -Command ^
"$lines = Get-Content -LiteralPath $env:source -ErrorAction Stop; " ^
"$csv = $lines -join $env:separator; " ^
"[System.IO.File]::WriteAllText($env:output, $csv)"
if %errorlevel% equ 0 (
echo [SUCCESS] Comma-separated output saved to "%output%".
) else (
echo [ERROR] PowerShell conversion failed.
pause
exit /b 1
)
pause
exit /b 0
The -join operator concatenates all array elements with the specified separator in a single operation, regardless of file size. Combined with -NoNewline, the output file contains exactly one line with no trailing newline character, which is ideal for feeding into tools that expect a clean single-line input.
Why Convert Multi-Line to Single-Line?
- Command Arguments: Many CLI tools accept a list of items separated by commas (e.g., a list of server names or service names passed as a single parameter).
- Web Queries: Converting a list of IDs into a single query parameter for an API call.
- Data Export: Preparing a list of data to be pasted into the BCC field of an email or as a single entry in a spreadsheet cell.
Best Practices
- Verify Source File: Always check that the input file exists before processing. A missing file will cause the
for /floop to silently produce an empty result. - The 8,191-Character Limit: A single Batch variable cannot exceed 8,191 characters. If your flattened list is longer than this, the Batch script will silently truncate the string. For large lists, always use the PowerShell method.
- Configurable Separator: Define the separator as a variable (
set "separator=,") rather than hardcoding it in the concatenation logic. This makes it easy to switch between comma-separated, semicolon-separated, pipe-separated, or any other format. - Special Characters in Values: If your line values contain the separator character itself (e.g., a comma inside a server description), you may need to wrap each item in quotes during concatenation (e.g.,
"item1","item2"). Without quoting, the consuming tool will misparse the boundaries between values. - Blank Lines: The Batch
for /floop skips blank lines, which means they will not appear as empty entries in the flattened string. The PowerShell method preserves blank lines, which would produce consecutive separators (e.g.,server1,,server3). Filter blank lines before joining if this is undesirable. - Empty File Handling: Always check whether the result is empty after processing. An empty source file or a file containing only blank lines should produce a clear warning rather than silently writing an empty output file.
- No Trailing Separator: The conditional logic in Method 1 (
if "!csv!" equ "") prevents a leading separator. The PowerShell-joinoperator inherently produces no leading or trailing separator. Always verify that your output does not have stray separators at either end.
Conclusion
Converting multi-line text into a single comma-separated string is a vital flattening technique for administrative automation. It allows you to bridge the gap between tools that output vertical lists and those that require horizontal inputs. By mastering this transformation, you ensure that your data remains fluid and adaptable, regardless of the formatting requirements of the next tool in your pipeline.