5

Given a CSV file,

h1 h2 h3
a  b  c
z  x  b

how to rename the first header to One and the third header to Three using command line tools, namely

One h2 Three
a   b  c
z   x  b
2
  • If you are familiar with VBScript you can do it easy: read the file, call Replace() - ready! Jan 15, 2016 at 10:35
  • Let's not reinvent the wheel here, it is something that is done so many times with solutions in pure BAT, VBS, Powershell.. etc. CSV is a text file so just google for 'file text replace in bat'.
    – Setekh
    Jan 15, 2016 at 11:03

4 Answers 4

5

This should do it:

https://stackoverflow.com/questions/11145270/bash-replace-an-entire-line-in-a-text-file

The header should just be the first line in your file, so if you use N = 1, and rewrite the line with the desired headers, so:

sed -i '1s/.*/One, h2, Three/' file.csv

will do it

4
  • 1
    Add that this is a *nix solution ;)
    – Setekh
    Jan 15, 2016 at 11:05
  • what is a nix solution?
    – sean read
    Jan 16, 2016 at 11:40
  • oh right, I get it now... en.wikipedia.org/wiki/Unix-like
    – sean read
    Jan 18, 2016 at 3:40
  • This is incorrect, as the CSV header can span multiple lines.
    – adius
    Jan 9, 2020 at 10:47
1

Sed has the "change" command c to replace the whole current line:

sed -i '1c\One h2 Three' file.csv

This works with GNU sed. Others seds might need the text to be entered on a separate line:

sed -i '1c\
One h2 Three' file.csv
1

Line-based solutions (such as sed-based) won't work for multiline csv headers.

So you need something to understand csv format.

For example with csvtool (ocaml):

echo 'My,New,Header'      > output.csv
csvtool drop 1 input.csv >> output.csv
-1

The below command should work

sed -i '1s/h1/One/;1s/h3/Three/;' file.csv

-i edits the file in place.

1 executes the operation in the first line.

s/h1/One/ substitutes h1 with One.

2
  • 1
    Welcome on the SU! What it does? And how?
    – peterh
    Apr 22, 2020 at 10:37
  • Welcome to Super User! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
    – MMM
    Apr 22, 2020 at 14:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .