简体   繁体   中英

batch file to remove a column in csv

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. Also I am wondering if there is a better way to do this. Thanks!

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
(
 FOR /f "delims=" %%a IN (q29441490.txt) DO (
  SET "line=%%a"
  SET "line=!line:,= , !"
  FOR /f "tokens=1,2*delims=," %%p IN ("!line!") DO (
   SET "line=%%p,%%r"
   SET "line=!line: , =,!"
   ECHO(!line!
  )
 )
)>u:\newfile.txt

GOTO :EOF

I used a file named q29441490.txt containing your data for my testing.

Produces u:\\newfile.txt

the separators between tokens are delimiter sequences , so ,, is seen as one separator, hence the fields appear moved by one place.

Grab each line, replace each , with , tokenise (you don't say explicitly, but you appear to want to eliminate the second column) so %%q gets the first column and %%r the remainder of the line following the second. Concatenate these, insert the comma and then reverse the substitution.

If you wanted to eliminate another column, then a different tokens element should be specified and the restructure of the line would need to be adjusted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM