-2

I wrote this code so I can remove a column from a csv file.

@echo off
setlocal enableextensions enabledelayedexpansion
type nul > tmp.txt
SET /A COUNT=0
for /F "tokens=*" %%A in (d.csv) do (
    set LINE="%%A"
    set /A COUNT+=1
    for /F "tokens=1,2,3,4,5,6,7,8,* delims=," %%a in (!LINE!) do (
        set row[0]=%%a
        set row[1]=%%b
        set row[2]=%%c
        set row[3]=%%d
        set row[4]=%%e
        set row[5]=%%f
        set row[6]=%%g
        set row[7]=%%h
)       

    echo !row[0]!,!row[2]!,!row[3]!,!row[4]!,!row[5]!,!row[6]! >>tmp.txt
        echo.
)
endlocal



Test file:
A1,B1,C1,D1,la la,,1
A2,B2,C2,D2, ,fef 3,
A3,B3,C3,D3,be be ,bo,bo 1
A4,B4,C4,D4,tu tu,tu 7,881

Output file:
A1,C1,D1,la la,1, 
A2,C2,D2, ,fef 3, 
A3,C3,D3,be be ,bo,bo 1 
A4,C4,D4,tu tu,tu 7,881 

I don't get why in the output file at the first line the ,, is eliminated and a , added at the end.

uoftcode
  • 27
  • 5
  • Not the only way, no. See [this page](http://www.dostips.com/forum/viewtopic.php?f=3&t=6184&mobile=desktop) for a solution using the MS Jet driver. Using that script, assuming you want to drop a column named col3, you could try `csv select col1, col2, col4, col5 into new.csv from old.csv` then overwrite old.csv with new.csv. It's probably actually less efficient than reading the file line-by-line though. :) – rojo Mar 18 '15 at 03:32
  • thanks for the suggestion.I will look into that as well..Meanwhile can you please take a look at my edit also ? :) – uoftcode Mar 18 '15 at 04:31
  • What is it that you are not understanding? `,,` is gone, because the value between those 2 commas (empty string) is the 6th field (counting from 0) & you are printing `row[6]` as last field in the output. There is no comma after that in your echo statement.. The last comma that you see is the comma after `row[5]` in your echo statement. – anishsane Mar 18 '15 at 04:37
  • @anishsane ..Isn't the `,,` 5th field in the input ? The output file completely skips it.. I don't get it why and it adds the a `,` at the end. Can you correct the code for me maybe so I can understand? Thanks! – uoftcode Mar 18 '15 at 04:45
  • my bad.. I miscounted... – anishsane Mar 18 '15 at 05:15

1 Answers1

0

Your code is doing what it is supposed to do... see @anishane comment. If what you want to do is replace an empty string with a space add this line before your first FOR loop to initialize each element of the array to a space.

for /L %%A in (0,1,7) do set "row[%%A]= "
RGuggisberg
  • 4,630
  • 2
  • 18
  • 27