Rockstar
Rockstar

Reputation: 2288

Add columns into a csv file using batch file

I have a csv file with the below contents.

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

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
)

Any help would be appriciated.

Upvotes: 0

Views: 8111

Answers (2)

user6811411
user6811411

Reputation:

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

  • you simply need to write the new header in the first row
  • and empty new columns in all other rows.

@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 

Sample output:

> 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,"","",""

Upvotes: 2

Stephan
Stephan

Reputation: 56155

for /f "tokens=1-4,* delims=," %%a in (input.csv) do (
    >>newfile.csv echo %%a,NewSecond,%%b,%%c,%%d,NewFifth,%%e
)

%%e is "token *", that means "the rest of the line"

Are you sure, you want to have the same strings on column 2 and 5 in every line?

Upvotes: 1

Related Questions