Rename CSV header using command line tools

13,389

Solution 1

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

Solution 2

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

Solution 3

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
Share:
13,389

Related videos on Youtube

elm
Author by

elm

Updated on September 18, 2022

Comments

  • elm
    elm over 1 year

    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
    
    • Leo Chapiro
      Leo Chapiro over 8 years
      If you are familiar with VBScript you can do it easy: read the file, call Replace() - ready!
    • Setekh
      Setekh over 8 years
      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
    Setekh over 8 years
    Add that this is a *nix solution ;)
  • sean read
    sean read over 8 years
    what is a nix solution?
  • sean read
    sean read over 8 years
    oh right, I get it now... en.wikipedia.org/wiki/Unix-like
  • adius
    adius over 4 years
    This is incorrect, as the CSV header can span multiple lines.
  • peterh
    peterh about 4 years
    Welcome on the SU! What it does? And how?
  • MMM
    MMM about 4 years
    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.