Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert header in a csv file with command line Windows

I have a .csv file with some data, for example:

a | b | c | d | e
f | g | h | i | f

I would like to insert a header in this file to indicate each field:

h1 | h2 | h3 | h4 | h5
a | b | c | d | e
f | g | h | i | l

I would like to do it from the Windows command line, how can I do?

like image 257
Daniele Quattrone Avatar asked Apr 27 '26 21:04

Daniele Quattrone


2 Answers

First, write the header to a new text file (escape the pipe symbol | using ^)

echo h1 ^| h2 ^| h3 ^| h4 ^| h5 > combined.csv

Then append the original file to this newly created file:

type originalfile.csv >> combined.csv

At last, you overwrite the original file with the content of the new file (including the header line)

type combined.csv > originalfile.csv
--or--
move /Y combined.csv originalfile.csv

Based on these answers: using batch echo with special characters and Easiest way to add a text to the beginning of another text file in Command Line (Windows)

like image 136
Stephan Bauer Avatar answered Apr 30 '26 16:04

Stephan Bauer


You can use Miller and run

mlr --csv --implicit-csv-header --fs "|" label h1,h2,h3,h4,h5 input.csv

to have

h1|h2|h3|h4|h5
a|b|c|d|e
f|g|h|i|f
  • --csv to set the format
  • --implicit-csv-header to declare that the input has no heading
  • --fs "|" to set the field separator
  • label h1,h2,h3,h4,h5 to set the heading
like image 37
aborruso Avatar answered Apr 30 '26 15:04

aborruso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!