Mandar Shinde
Mandar Shinde

Reputation: 1745

How to read values in a particular column of a CSV file in Batch?

I am planning to write a batch script wherein I need to scan the values from a particular column of a CSV file one by one and store them in a variable for further processing.

Say, following is the CSV file:

A1, B1, C1, D1, E1
A2, B2, C2, D2, E2
A3, B3, C3, D3, E3
.., .., .., .., ..

I have to read D1, execute a command using it's value, read D2, execute a command, and so on.

How can this be achieved?

Upvotes: 2

Views: 9940

Answers (2)

Ashish
Ashish

Reputation: 101

Use this, It will solve your problem :

CSVReader reader = null;

try 
{
    reader = new CSVReader(new FileReader(dir));
    String[] row;
    List<?> content = reader.readAll();

    for (Object object : content) 
    {
        row = (String[]) object;
        for (int i = 0; i < row.length; i++) 
        {
            // display CSV values
                System.out.println("Cell column index: " + i);
                System.out.println("Cell Value: " + row[i]);
                System.out.println("-------------");
        }
    }
}catch (FileNotFoundException e) 
{
    System.err.println(e.getMessage());
}
catch (IOException e) {
    System.err.println(e.getMessage());
}

Upvotes: -1

TessellatingHeckler
TessellatingHeckler

Reputation: 28963

Why is your "Comma Separated Value" file ... not comma separated? Are they tab or space separated? Are there spaces in the values themselves?

for /f "tokens=4 delims=, " %%a in (data.csv) do (
    echo run command here "%%a"
)
  • This runs for each line in the file
  • "delims=, " splits the line on commas or space characters
  • tokens=4 selects column 4 after the split

Upvotes: 4

Related Questions