I want to add a row of headers to an existing CSV file, editing in place. How can I do this?
echo 'one, two, three' > testfile.csv
and I want to end up with
column1, column2, column3
one, two, three
Changing the initial CSV output is out of my hands.
Any standard command will do. The important thing is the file is edited in place, and the line is inserted at the beginning of the file.
To answer your original question, here's how you do it with sed:
The "1i" command tells sed to go to line 1 and insert the text there.
The -i option causes the file to be edited "in place" and can also take an optional argument to create a backup file, for example
would keep the original file in "testfile.csv~".
This adds custom text at the beginning of your file:
As far as I understand, you want to prepend
column1, column2, column3
to your existingone, two, three
.I would use
ed
in place ofsed
, sincesed
write on the standard output and not in the file.The command:
should do the work.
perl -i
is worth taking a look as well.Use perl -i, with a command that replaces the beginning of line 1 with what you want to insert (the .bk will have the effect that your original file is backed up):
This doesn't use sed, but using >> will append to a file. For example:
Edit: To prepend to a file, try something like this:
I found this through a quick Google search.
sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just
?