How to Convert a Comma-Separated Line to Multiple Lines in Batch Script
The opposite of "flattening" a file is "expanding" it. If you receive a string of data from an API, a database export, or a config file that is stored horizontally (e.g., user1,user2,user3), you often want to convert it to a vertical list (one per line). Vertical lists are much easier to process with for /f loops and easier for humans to read and audit.
In this guide, we will demonstrate how to split a comma-separated string into multiple lines using the for command.
Method 1: The Substitution and Loop Approach (Best for Files)
This method replaces commas with spaces and then uses a for loop to iterate through the resulting tokens.
Implementation Script
@echo off
setlocal disabledelayedexpansion
set "source=CSV_Line.txt"
set "dest=Vertical_List.txt"
:: Verify source file exists
if not exist "%source%" (
echo [ERROR] Source file "%source%" not found.
pause
exit /b 1
)
echo Splitting comma-separated values from "%source%"...
:: Read the single CSV line from the file, replace commas with
:: spaces, then iterate through the resulting tokens
(
for /f "usebackq delims=" %%A in ("%source%") do (
set "csvLine=%%A"
setlocal enabledelayedexpansion
set "csvLine=!csvLine:,= !"
for %%B in (!csvLine!) do (
echo(%%B
)
endlocal
)
) > "%dest%"
echo [SUCCESS] Values expanded to "%dest%".
pause
exit /b 0
The inner for %%B in (...) loop uses Batch's default token splitting and also expands wildcard characters (* and ?) against filenames in the current directory. If any of your CSV values contain * or ?, they will be replaced with matching filenames. Additionally, values containing spaces will be split into multiple tokens. For data that may contain spaces, wildcards, or other special characters, use the PowerShell method (Method 3).
The script uses the delayed expansion toggle pattern: the CSV line is set with delayed expansion disabled (set "csvLine=%%A") to preserve literal ! characters. The comma-to-space substitution and iteration are then performed with delayed expansion enabled to safely handle special characters during the replacement step.
Method 2: The Direct Variable Split (Best for Inline Strings)
If you have a comma-separated string already stored in a variable, you can replace commas with spaces and loop through the result directly.
Implementation Script
@echo off
setlocal enabledelayedexpansion
set "str=Red,Green,Blue,Yellow"
set "dest=colors.txt"
echo Splitting inline CSV string...
:: Replace commas with spaces to create space-delimited tokens
set "str=!str:,= !"
(
for %%A in (!str!) do (
echo(%%A
)
) > "%dest%"
echo [SUCCESS] Values expanded to "%dest%".
pause
exit /b 0
Method 2 is suitable for short, controlled strings where you know the values do not contain spaces, wildcards, or special characters. For user-supplied or external data, always validate the content or use Method 3.
Method 3: The PowerShell Bridge (Recommended for Complex Data)
PowerShell has a dedicated -split operator that reliably handles complex CSV strings, including values with spaces, special characters, and quoted fields.
Implementation Script
@echo off
setlocal
set "source=line.txt"
set "dest=list.txt"
:: Verify source file exists
if not exist "%source%" (
echo [ERROR] Source file "%source%" not found.
pause
exit /b 1
)
echo Splitting comma-separated values from "%source%"...
:: -split ',' splits on every comma and outputs each segment as a line
:: Trim() removes leading/trailing whitespace from each value
powershell -NoProfile -Command ^
"$line = Get-Content -Path '%source%' -Raw; " ^
"$values = $line -split ','; " ^
"$trimmed = $values | ForEach-Object { $_.Trim() } | " ^
" Where-Object { $_ -ne '' }; " ^
"$trimmed | Set-Content -Path '%dest%' -Encoding UTF8"
if %errorlevel% equ 0 (
echo [SUCCESS] Values expanded to "%dest%".
) else (
echo [ERROR] Split operation failed.
pause
exit /b 1
)
pause
exit /b 0
The PowerShell method includes .Trim() on each value to remove leading and trailing whitespace. This handles messy input like A, B, C (with spaces after commas) that would produce lines with leading spaces in the Batch methods. The Where-Object { $_ -ne '' } filter also removes empty entries caused by trailing commas or consecutive commas.
Why Expand a Single Line to Multiple Lines?
- Iterative Processing: Batch is built to process files line-by-line. Turning a long string into a vertical list allows you to use
for /fto perform a task for every item. - Readability: A list of 100 email addresses is impossible to audit on a single horizontal line; a vertical list is easy to scan.
- Cross-Tool Compatibility: Many Windows commands (like
nslookuportaskkill) work best when fed one input per line via a text file redirect.
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 empty output. - Commas Within Values: If your data contains commas within the actual values (e.g., a name like
"Doe, John"), the Batch methods will split the value incorrectly at the embedded comma. For quoted CSV data, use PowerShell'sImport-Csvcmdlet, which handles the full CSV specification including quoted fields. - Wildcard Expansion: The Batch
for %%B in (...)loop expands*and?against the filesystem. A value like*.logwould be replaced with matching filenames in the current directory. If your data may contain wildcards, use Method 3. - String Length Limit: Variables in Batch have an 8,191-character limit. If your horizontal string is longer than this, the Batch methods will silently truncate the data. Use Method 3 for long strings.
- Leading Whitespace: Converting
A, B, C(with spaces after commas) using the Batch methods will produce lines with leading spaces. The PowerShell method includes.Trim()to handle this automatically. In Batch, you would need additional logic to strip leading spaces from each token. - Empty Values: Consecutive commas (e.g.,
A,,C) represent an empty value in standard CSV. The Batch methods will silently skip the empty value, producing only two lines instead of three. The PowerShell method can detect and either preserve or filter empty values depending on your requirements.
Conclusion
Converting comma-separated strings into multiple vertical lines is a standard expansion technique used in data cleanup and system integration. By using the tokenization capabilities of the for loop for simple data or the robust splitting capabilities of PowerShell for complex data, you can unlock the information stored in horizontal strings and turn it into a manageable, line-by-line inventory ready for automated action.