0

I have the next batch file:

@echo off
setlocal enabledelayedexpansion
set lastpart=

for /F "tokens=2 delims=," %%f in (test.csv) do (
set lastPart= %%f
echo !lastPart!
pause
)

And the test.csv:

a1,,a3,,a5
b1,b2,b3,b4,b5
,,c3,,
,d2,,d4,
,,,,

My real output is: a3,b2,d2. Output I need: empty, b2, empty, d2, empty. The problem is that de loop not read empty tokens. Is there a property or something so the loop not avoid empty tokens? The loop always must have 5 tokens per line

Thanks

user3240604
  • 407
  • 1
  • 8
  • 22
  • Your real output should be **a3**,**b2**,**d4**. They aren't empty tokens, they aren't tokens. – Compo Nov 21 '16 at 17:37
  • @Compo I think the OP's real question could be rephrased as "How do you use Batch commands to read CSV files". And CSV files certainly do have empty tokens. – Klitos Kyriacou Nov 21 '16 at 17:44
  • @KlitosKyriacou, I would suggest that the CSV has fields, not tokens and that those fields are separated by comma delimiters. – Compo Nov 21 '16 at 17:52
  • Use PowerShell. It has built-in commands for handling CSV files. Much, much easier. – Bill_Stewart Nov 21 '16 at 17:56

1 Answers1

3

for /F treats consecutive delimiters as one. To avoid that, you could replace each delimiter , by "," and enclose each full line by "", so each item appears as being enclosed within "", which can easily be removed finally by the ~ modifier of the for /F variable:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "lastpart="

for /F "usebackq delims=" %%L in ("test.csv") do (
    set "LINE=%%L"
    setlocal EnableDelayedExpansion
    set LINE="!LINE:,=","!"
    for /F "tokens=2 delims=," %%F in ("!LINE!") do (
        endlocal
        set "lastpart=%%~F"
        setlocal EnableDelayedExpansion
        echo(!lastpart!
    )
    endlocal
)
endlocal

This might not work properly if the data contain , characters by themselves (remember that , is not considered as delimiter in case a field is enclosed within "" in the original CSV file).

The toggling of delayed expansion is done to not lose any exclamation marks in the data.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • After I posted my answer, the question has been marked as a duplicate of [this question](http://stackoverflow.com/q/17556976), so I copied my answer [there](http://stackoverflow.com/a/40729187) and slightly adapted it; I am going to keep this one here until a moderator advices me to delete it... – aschipfl Nov 21 '16 at 21:09