0

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.

1
  • 1
    Your sample csv isn't valid - there are three columns in the header but the comma at the end of the rows marks an empty 4th column. Processing a csv file with for /f with possible empty columns ,, will fail because for /f ignores leading delimiters and treats successive delimiters as only one. Commented May 26, 2017 at 13:01

2 Answers 2

2

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,"","",""
Sign up to request clarification or add additional context in comments.

Comments

1
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?

5 Comments

Not exactly, what I want is, to add headers in 2nd and 5th position and the header value should not be same. I checked your solution it worked in context of the column position but I want empty values for the newly added header.
as we speak of empty values - may there be such in input.csv? That could ruin newfile.csv
ah! so is there any way we can add only headers but the header columns shouldn't have any value in it.
yes: echo %%a,,%%b,%%c,%%d,,%%e. Note: will ruin your outputfile, if there are already emty values (because consecutive delimiters are treated as one)
I got the empty columns but now I lost the header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.