批处理文件以删除csv中的列 [英] batch file to remove a column in csv

查看:356
本文介绍了批处理文件以删除csv中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码,以便可以从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

我使用了一个名为q29441490.txt的文件,其中包含您的数据用于测试.

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

产生u:\ newfile.txt

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.

抓住每行,用,标记代替每一个,(您没有明确说,但您似乎想消除第二列),因此%%q获得第一列,而%%r获得其余第二行之后的行.将它们串联起来,插入逗号,然后反向替换.

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.

如果要删除另一列,则应指定其他tokens元素,并且需要调整行的结构.

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.

这篇关于批处理文件以删除csv中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆