user3775630
user3775630

Reputation: 1

How to fetch second row, second column from a .csv file?

I have a CSV file that has looks something like below:

Order ID,Order Date,Ship Date,Ship Mode
CA-2011-103800,2013-01-03,2013-01-07 00:00:00,Standard Class
CA-2011-112326,2013-01-04,2013-01-08 00:00:00,Standard Class

All I need is to get from first data row the order date, i.e. 2013-01-03 in this case.

I tried the code below which doesn't solve the problem.

set file=output.csv
for /f "skip=1 tokens=2 delims=," %%A in (%file%) do (echo %%A)

I am a beginner. Can anyone help me out with this?

Upvotes: 0

Views: 741

Answers (3)

rojo
rojo

Reputation: 24466

Just for fun, here's another alternative. You can redirect your csv file into a loop containing two set /P statements -- one to consume the first line, and the second to set a variable to the second line. Then for the line that was captured, use variable substring substitution to strip away *, and ,*.

@echo off & setlocal
(
    set /P "="
    set /P "val="
) < "output.csv"

set "val=%val:*,=%"
echo %val:,=&rem;%

But really, your attempted solution is almost correct. All that's needed is to break out of the loop after its first iteration.

@echo off & setlocal
set "file=output.csv"
for /f "usebackq skip=1 tokens=2 delims=," %%A in ("%file%") do echo %%A && exit /b

Upvotes: 2

user7818749
user7818749

Reputation:

Something like this using more command to skip the first line and simply get the second token each time:

to get only the first value:

@echo off
set "file=output.csv"
for /f "tokens=2 delims=," %%i in ('type order.txt ^| more +1') do echo %%i & goto next
:next
pause

or to get each second column's value:

@echo off
set "file=output.csv"
for /f "tokens=2 delims=," %%i in ('type %file% ^| more +1') do echo %%i
pause

Upvotes: 0

John Kens
John Kens

Reputation: 1679

This can be done VERY easy by creating an array out of the data from file.csv. By using !Line[2]! we can grab any line of the .csv file we want. Simply change the Row & Column configurations to however you need. This can be very useful for searching a .csv file.

@echo off
@setlocal enabledelayedexpansion

Rem | Row & Column Information
Set "Row=2"
Set "Column=2"

Rem | Turn Lines To Array Strings
for /f "tokens=* delims=" %%A in ('Type file.csv') do (
    set /a "count+=1"
    set "Line[!count!]=%%A"
)

Rem | Grab Second Column From Second Row
for /f "tokens=%Column% delims=," %%A in ('Echo !Line[%Row%]!') do (
    set "Data=%%A"
)

Echo Second Row, Second Column Data: %Data%

I left a new Rem notes to help you along in the script process.

Upvotes: 2

Related Questions