Ben Richard
Ben Richard

Reputation: 23

Add columns in CSV file using windows batch script

i have a csv file with pipe (|) delimiter like below. Column header defines by 6 columns but rows value has 7 columns.

Column 1|Column 2|Column 3|Column 4|Column 5|Column 6
Value 1 |Value 2 |Value 3 |Value 4 |Value 5 |Value 6 |0
Value 11|Value 12|Value 13|Value 14|Value 15|Value 16|0

So i try to make new column with windows batch script.

Here is my code :

@Echo off&Setlocal EnableExtensions EnableDelayedExpansion
Set Row=0
( for /f "tokens=1-7 delims=|" %%A in (BAT0071.csv) do (
    Set /A Row+=1
    If !Row! lss 2 (Rem new header
      echo %%A^|%%B^|%%C^|%%D^|%%E^|%%F^|IgnoreLast
    ) Else (Rem insert duplicate values
      echo %%A^|%%B^|%%C^|%%D^|%%E^|%%F^|%%G
    )
  )
) >"BAT0071.tmp"
move /y "BAT0071.tmp" "BAT0071.csv"
PAUSE

The problem is if all rows value filled then its fine, but example value 3 in first row empty then the structure changed like below.

Column 1|Column 2|Column 3|Column 4|Column 5|Column 6|IgnoreLast
Value 1 |Value 2 |Value 4 |Value 5 |Value 6 |0|
Value 11|Value 12|Value 13|Value 14|Value 15|Value 16|0

How to make empty value still in position?

Expected result

Column 1|Column 2|Column 3|Column 4|Column 5|Column 6|IgnoreLast
Value 1 |Value 2 |Value 3 |Value 4 |Value 5 |Value 6 |0
Value 11|Value 12|Value 13|Value 14|Value 15|Value 16|0

Upvotes: 2

Views: 829

Answers (1)

user7818749
user7818749

Reputation:

In this particular case, because you do not add additional values, we simply do not use delims:

@Echo off&Setlocal EnableExtensions EnableDelayedExpansion
Set Row=0
(for /f "delims=" %%a in (BAT0071.csv) do (
    Set /A Row+=1
    If !Row! equ 1 (
      echo %%a^|IgnoreLast
    ) else (
      echo %%a
    )
 )
)>BAT0071.tmp
move /y "BAT0071.tmp" "BAT0071.csv"
PAUSE

Upvotes: 1

Related Questions