Skip to main content

How to Parse a CSV File in Batch Script

CSV (Comma-Separated Values) is a standard format for data exchange, and batch scripts are often used to automate the processing of these files. Whether it's reading a list of users, processing records, or importing data, parsing a CSV file line by line and column by column is a fundamental scripting skill. The primary tool for this in batch is the FOR /F command.

This guide will teach you how to use FOR /F to parse simple CSV files, how to handle common features like header rows and empty fields, and explain the critical limitation of batch scripting when dealing with complex CSVs. Crucially, it will also provide a superior, modern solution using PowerShell for handling real-world, messy data reliably.

The Core Command: FOR /F

The FOR /F command is the workhorse of file parsing in batch scripts. It reads a file line by line and, for each line, can split it into parts (tokens) based on a specified delimiter.

The key options for parsing CSVs are:

  • delims=,: Specifies the comma as the delimiter. FOR /F will use it to split the line into columns.
  • tokens=1,2,3*: Specifies which columns (tokens) you want to capture.
    • 1,2,3 would capture the first three columns into %%A, %%B, and %%C.
    • The asterisk (*) is a wildcard that tells FOR /F to capture all remaining text on the line into the next variable. So, tokens=1,2* would put column 1 in %%A and everything else (columns 2, 3, 4, etc.) into %%B.

Basic Example: Reading a Simple CSV

Let's start with a simple, well-behaved CSV file.

Consider the following file users.csv

users.csv
ID,Username,Status
101,Alice,Active
102,Bob,Inactive
103,Charlie,Active

This script will read each line and echo the content of the three columns.

@ECHO OFF
ECHO Processing CSV file...
ECHO.

FOR /F "tokens=1,2,3 delims=," %%A IN (users.csv) DO (
ECHO User ID: %%A, Name: %%B, Status: %%C
)

Output:

Processing CSV file...

User ID: ID, Name: Username, Status: Status
User ID: 101, Name: Alice, Status: Active
User ID: 102, Name: Bob, Status: Inactive
User ID: 103, Name: Charlie, Status: Active

This works, but notice it's also processing the header row as if it were data.

Handling Common CSV Features

Skipping the Header Row

Most CSV files have a header row that describes the columns. The FOR /F command provides a simple skip option to ignore it.

@ECHO OFF
REM The 'skip=1' option tells the loop to ignore the first line of the file.
FOR /F "skip=1 tokens=1,2,3 delims=," %%A IN (users.csv) DO (
ECHO User ID: %%A, Name: %%B, Status: %%C
)

Output (The header row is now correctly ignored)

User ID: 101, Name: Alice, Status: Active
User ID: 102, Name: Bob, Status: Inactive
User ID: 103, Name: Charlie, Status: Active

Handling Empty Fields

Real-world data is often incomplete. A CSV might have empty fields, represented by two commas next to each other (,,). FOR /F can handle this gracefully.

data.csv
Product,Quantity,Notes
Apples,50,Fresh
Oranges,,Needs restocking
Pears,25,
@ECHO OFF
FOR /F "skip=1 tokens=1,2,3 delims=," %%A IN (data.csv) DO (
ECHO Product: [%%A], Quantity: [%%B], Notes: [%%C]
)

As you can see in the output, the FOR /F loop correctly assigns the variables, leaving the ones for empty fields blank.

Product: [Apples], Quantity: [50], Notes: [Fresh]
Product: [Oranges], Quantity: [], Notes: [Needs restocking]
Product: [Pears], Quantity: [25], Notes: []

Critical Limitation: When Batch Fails

The pure batch method has a fatal flaw: it cannot correctly parse fields that are quoted and contain the delimiter character. This is a very common scenario in real-world CSV files.

Problem: Quoted Fields Containing Commas

Consider a CSV with a "City, State" field.

locations.csv
ID,Contact,Location
1,"Smith, John","New York, NY"
2,"Doe, Jane","Chicago, IL"

A simple batch parser will break this data.

Let's see the error:

@ECHO OFF
REM This will FAIL to parse correctly.
FOR /F "skip=1 tokens=1,2,3 delims=," %%A IN (locations.csv) DO (
ECHO ID: [%%A], Contact: [%%B], Location: [%%C]
)

Output (The data is corrupted! The parser splits "Smith, John" into two columns.)

ID: [1], Contact: ["Smith], Location: [ John"]
ID: [2], Contact: ["Doe], Location: [ Jane"]
note

There is no reliable, pure-batch solution for this common problem. Any attempt to solve it with batch code becomes incredibly complex and will still fail on other edge cases.

The Superior Solution: Using PowerShell for Reliability

For any CSV file that is not extremely simple, the correct and modern solution is to call PowerShell from your batch script. PowerShell has a built-in, robust CSV parser that handles quotes, commas, and other complexities flawlessly.

This script uses PowerShell's Import-Csv cmdlet to correctly read the file and print the data.

@ECHO OFF
SET "CSV_FILE=locations.csv"

powershell -Command "Import-Csv '%CSV_FILE%' | ForEach-Object { Write-Host ('ID: [' + $_.ID + '], Contact: [' + $_.Contact + '], Location: [' + $_.Location + ']') }"

Output (The data is parsed perfectly.)

ID: [1], Contact: [Smith, John], Location: [New York, NY]
ID: [2], Contact: [Doe, Jane], Location: [Chicago, IL]
note

Here, Import-Csv treats the file as an object, and $_ represents the current row. We can access columns by their header names (e.g., _$.ID).

Practical Example: Processing User Data with PowerShell

This batch script uses the PowerShell method to iterate through a CSV and perform an action for each user.

@ECHO OFF
SET "CSV_FILE=users.csv"

ECHO Starting user processing...
powershell -Command ^
"Import-Csv '%CSV_FILE%' | ForEach-Object { " ^
"if ($_.Status -eq 'Active') { " ^
"Write-Host ('Processing active user: ' + $_.Username)" ^
"} " ^
"}"

ECHO Done.
note

This hybrid approach gives you the power of a real CSV parser while staying within the familiar structure of a batch file.

Conclusion

Parsing CSV files in batch scripts presents a clear choice between simplicity and robustness.

  • The FOR /F method is acceptable for very simple CSV files that you know will never contain quoted commas. It's quick, built-in, and useful for basic automation.
  • For any real-world or potentially complex CSV file, the pure batch method is unreliable and should be avoided. The PowerShell Import-Csv command is the correct, modern, and professional tool for the job.

By embedding a PowerShell one-liner in your batch script, you get the best of both worlds: a simple batch file that can correctly handle the complexities of the CSV format.