Batch script skipping blank entries in a .CSV when delim is ','

后端 未结 2 1735
無奈伤痛
無奈伤痛 2020-12-12 00:23

I have a .CSV that I am trying to sort through to create another file from the data, but when I run it through, it skips blank entries. For example, if a line is valu

2条回答
  •  一生所求
    2020-12-12 01:01

    As jeb already mentiones in his answer, for /F treats consecutive delimiters as one. To avoid that, you could replace each delimiter , by "," and enclose each full line by "", so each field appears as being enclosed within "", which can easily be removed finally by the ~ modifier of the for /F variable; so there is no need to do any more string manipulations (like sub-string expansion) later on:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    for /F "usebackq delims=" %%# in ("file.csv") do (
        set "LINE=%%#"
        setlocal EnableDelayedExpansion
        for /F "tokens=1-4 delims=," %%A in (^""!LINE:,="^,"!"^") do (
            endlocal
            echo Field 1: %%~A
            echo Field 2: %%~B
            echo Field 3: %%~C
            echo Field 4: %%~D
            setlocal EnableDelayedExpansion
        )
        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.

提交回复
热议问题