使用批处理文件将列添加到csv文件中 [英] Add columns into a csv file using batch file

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

问题描述

我有一个包含以下内容的csv文件.

I have a csv file with the below contents.

userid,userRole,ContentType
1,text1,value1,
2,text2,value2,

我想编写一个批处理文件,以在csv文件的开头添加一些列标题.我使用这段代码来仅添加一个额外的列.是否可以根据列位置添加多个列?

I want to write a batch file to add few column headers at the beginning of the csv file. I had this piece of code working to add only one additional column. Is it possible to add multiple columns based on column position?

例如我想在第二和第五位置添加一个新列.

e.g. I want to add a new column in 2nd and 5th position.

@echo off > newfile.csv & setLocal enableDELAYedeXpansion
for /f "tokens=* delims= " %%a in (input.csv) do (
>> newfile.csv echo.FirstName,%%a
)

将寻求任何帮助.

推荐答案

尽管注释中没有空列,但我的提示仍然存在:

Despite my hints in the comment provided there are no empty columns:

  • 您只需要在第一行中写入新的标题
  • 并在所有其他行中清空新列.
@Echo off&Setlocal EnableExtensions EnableDelayedExpansion
Set Row=0
( for /f "tokens=1-5 delims=," %%A in (input.csv) do (
    Set /A Row+=1
    If !Row! lss 2 (Rem new header
      echo %%A,NewSecond,%%B,%%C,%%D,NewFifth,%%E
    ) Else (Rem insert new empty columns
      echo %%A,"",%%B,%%C,%%D,"",%%E
    )
  )
) >newfile.csv 

示例输出:

> type *.csv
input.csv

userid,userRole,ContentType,Col4,Col5
1,text1,value1,"",""
2,text2,value2,"",""

newfile.csv

userid,NewSecond,userRole,ContentType,Col4,NewFifth,Col5
1,"",text1,value1,"","",""
2,"",text2,value2,"","",""

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

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