Skip to main content

How to Reorder Columns in a CSV File in Batch Script

CSV files often arrive in a format that is not ideal for your specific processing needs. For example, a system might export data as Date,Username,Action, but your audit tool requires Username,Action,Date. Column reordering is the process of rearranging these vertical segments to match a required schema.

In this guide, we will demonstrate how to swap and reorder columns using the tokens parameter in Batch and a more flexible PowerShell approach.

Method 1: The Token Swap (Native Batch)

The for /f command can capture multiple tokens simultaneously and assign them to sequential variables (%%A, %%B, %%C, etc.). By echoing these variables in a different order, you effectively reorder the columns.

Given a CSV file with the following structure:

RawData.csv
Date,Username,Action
2026-01-15,jsmith,Login
2026-01-15,bjones,Upload
2026-01-16,apark,Delete

This script reorders the output to Username,Date,Action.

@echo off
setlocal disabledelayedexpansion

set "Source=RawData.csv"
set "Output=ReorderedData.csv"

:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)

echo Reordering columns in "%Source%"...

:: tokens=1,2,* captures:
:: %%A = Column 1 (Date)
:: %%B = Column 2 (Username)
:: %%C = Everything else (Action and any columns beyond it)
(
for /f "usebackq tokens=1,2,* delims=," %%A in ("%Source%") do (
set "col1=%%A"
set "col2=%%B"
set "col3=%%C"
setlocal enabledelayedexpansion
:: Echo Column 2 first, then Column 1, then the rest
echo(!col2!,!col1!,!col3!
endlocal
)
) > "%Output%"

echo [SUCCESS] Reordered CSV saved to "%Output%".
pause
exit /b 0

For example, the output file ReorderedData.csv will be:

ReorderedData.csv
Username,Date,Action
jsmith,2026-01-15,Login
bjones,2026-01-15,Upload
apark,2026-01-16,Delete
warning

The for /f command assigns token variables to sequential letters starting from your loop variable, not to letters matching the column positions. With tokens=1,2,* and loop variable %%A, column 1 is %%A, column 2 is %%B, and the remainder is %%C. The reordering is achieved entirely by changing the order in the echo statement.

tip

The script uses the delayed expansion toggle pattern: each column value is set with delayed expansion disabled (set "col1=%%A", etc.) to preserve literal ! characters in the data. The values are then output with delayed expansion enabled (echo(!col2!,!col1!,!col3!) to safely handle &, |, >, <, and other special characters that would break a direct echo %%B,%%A,%%C approach.

Reordering columns by index in Batch is manual and error-prone for files with many columns. PowerShell's Select-Object allows you to define the exact order of columns by their header names, making the script much more readable and robust.

@echo off
setlocal

set "Source=inventory.csv"
set "Dest=new_inventory.csv"

:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)

echo Reordering columns in "%Source%"...

:: Select-Object lists the columns in the exact desired output order
:: Any columns not listed are excluded from the output
powershell -NoProfile -Command ^
"Import-Csv -Path '%Source%' | " ^
"Select-Object 'Name','Serial','Status' | " ^
"Export-Csv -Path '%Dest%' -NoTypeInformation -Encoding UTF8"

if %errorlevel% equ 0 (
echo [SUCCESS] Reordered CSV saved to "%Dest%".
) else (
echo [ERROR] Reorder operation failed.
pause
exit /b 1
)
pause
exit /b 0

Consider this input file inventory.csv:

inventory.csv
Status,Name,Serial
Active,Laptop A,SN10001
Inactive,Laptop B,SN10002
Active,Printer X,PR30055
Maintenance,Router Z,RTR77881

The output file new_inventory.csv will be:

new_inventory.csv
Name,Status,Serial
Laptop A,Active,SN10001
Laptop B,Inactive,SN10002
Printer X,Active,PR30055
Router Z,Maintenance,RTR77881
info

The Select-Object cmdlet both reorders and filters columns in a single step. Only the columns you list are included in the output, and they appear in the exact order specified. If a listed column name does not exist in the source file, it will appear in the output with empty values rather than producing an error. Always verify that your column names exactly match the source file headers, including capitalization and spacing.

Why Reorder CSV Columns?

  1. Tool Requirements: Some command-line tools expect the primary key (like an ID or PIN) to be in the very first column.
  2. Human Readability: Moving the most important columns (e.g., "Error Message") to the left makes the file significantly easier for an administrator to scan quickly.
  3. Database Imports: SQL and other database engines require the CSV columns to perfectly match the column order of the destination table for a successful bulk insert.

Best Practices

  1. Verify Source File: Always check that the input file exists before processing. A missing file will cause the for /f loop to silently produce empty output.
  2. Header Integrity: The Batch method processes the header row identically to data rows, so the header will be reordered along with the data. Always verify that the output header still correctly labels each column after the swap.
  3. Quoted Fields: If any cell contains the delimiter character within its value (like "Doe, John"), the Batch delims=, will split that cell into two separate columns, corrupting the row and shifting all subsequent column positions. Use Method 2 for any CSV that may contain quoted fields.
  4. Wildcard Token Limitation: The * wildcard in tokens=1,2,* captures the entire remainder of the line as a single unsplit string. This works for reordering the first few columns while keeping the rest intact, but it does not allow you to selectively reorder columns within the remainder. For full control over all column positions, either specify each token individually (e.g., tokens=1,2,3,4) or use Method 2.
  5. Token Limits: Batch for /f loops support tokens up to index 31. If your CSV has more than 31 columns, you must use PowerShell.
  6. Column Name Verification: When using Method 2, ensure the column names in Select-Object exactly match the header names in the source CSV. A misspelled column name will produce an empty column in the output rather than an error, silently corrupting the result.
  7. Encoding: Include -Encoding UTF8 in the PowerShell Export-Csv command to prevent non-ASCII characters from being corrupted by the default encoding.

Conclusion

Reordering columns is a high-impact data transformation that turns generic exports into targeted, tool-specific inputs. Whether you use the simple variable-swapping technique in Batch for small well-structured files or the professional header-based selection in PowerShell for complex reports, the ability to reorganize your data vertically is essential for seamless system integration and efficient automated reporting.