Batch file tokens ignore empty delimiters

后端 未结 2 1799
情深已故
情深已故 2021-01-07 06:12

I am trying to load a column from a CSV file into a variable. My CSV file contains empty columns so can have ,, which seems to be ignored by the following:

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-07 07:09

    for treats consecutive delimiters as one. In most cases, this is helpful. Sometimes it is not.

    So you have to write your lines in a way, that for can handle as you intended.

    Read every line of your file as a whole, add a quote at the beginning and at the end and replace every , with ",", resulting in

    "chris","","steve","deon","bryan","mark","anthony"
    

    This can happily be parsed with another for. The tilde in %%~b removes the surrounding quotes.

    @echo off
    setlocal enabledelayedexpansion
    FOR /F "tokens=*" %%a in (csvfile.csv) do (
      set line="%%a"
      for /f "tokens=3 delims=," %%b in ("!line:,="^,"!") do echo %%~b
    )
    

提交回复
热议问题