Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert a line in csv file

Tags:

I have a huge csv file (on order of terabytes).

Now, I want to insert one row which is a header to the the top.

For example if input.csv looks like this:

 1,2,3,4  22,3,23,1 

I want it to look like

id1,id2,id3,id4  1,2,3,4  and so on 

How do i do this from shell, terminal, awk, bash?/

like image 871
frazman Avatar asked Nov 15 '12 17:11

frazman


People also ask

How do I add a new line to a CSV file?

Windows standard CR+LF or Unix-like systems (Linux, Mac) standard LF may be used as new line character.

How do I add a line to a CSV file in Python?

If you need to append row(s) to a CSV file, replace the write mode ( w ) with append mode ( a ) and skip writing the column names as a row ( writer. writerow(column_name) ).


1 Answers

In place, using sed:

sed -i 1i"id1,id2,id3,id4" file.csv 

edit:

As @Ed Morton points out, using sed with the -i switch sed edits the file in place, and can therefore be dangerous when editing large files. If you supply a prefix after the -i option then sed creates a backup. So something like this would be safer:

sed -i.bak 1i"id1,id2,id3,id4" file.csv 

The original file will then be located in file.csv.bak

like image 92
Lee Netherton Avatar answered Apr 05 '23 11:04

Lee Netherton