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
Related videos on Youtube
Author by
elm
Updated on September 18, 2022Comments
-
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 toThree
using command line tools, namelyOne h2 Three a b c z x b
-
Leo Chapiro over 8 yearsIf you are familiar with VBScript you can do it easy: read the file, call Replace() - ready!
-
Setekh over 8 yearsLet'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 over 8 yearsAdd that this is a *nix solution ;)
-
sean read over 8 yearswhat is a nix solution?
-
sean read over 8 yearsoh right, I get it now... en.wikipedia.org/wiki/Unix-like
-
adius over 4 yearsThis is incorrect, as the CSV header can span multiple lines.
-
peterh about 4 yearsWelcome on the SU! What it does? And how?
-
MMM about 4 yearsWelcome 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.