Tuesday, September 11, 2012

How can I add a line to a file in a shell script (with sed)? - Stack Overflow


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
(nb changing the initial CSV output is out of my hands)
EDIT: I originally had this as 'using sed' but 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. Thanks,
share|edit



To answer your original question, here's how you do it with sed:
sed -i '1icolumn1, column2, column3' testfile.csv
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
sed -i~ '1icolumn1, column2, column3' testfile.csv
would keep the original file in "testfile.csv~".
share|edit
Which version of Unix? This does not work on Mac OS X Leopard, which is certified 'Single UNIX Specification V3'. – mouviciel Jan 29 '09 at 19:28
I use Linux. Apparently BSD sed (including OS X) requires an argument for -i (and should probably be separate like normal arguments). Try replacing the command with "sed -i '~' ...". If that works, I'll edit the answer. – Matthew Crumley Jan 29 '09 at 20:45
Thank you. I suspected this, but then I fail to make the i command work. I tried inline command (without or with -e) and script command (with -f) but I get: sed: rename(): Not a directory. You don't need to edit the answer as long as it is helpful for the asker. – mouviciel Jan 29 '09 at 21:24
Great, but i think you should note the "1i" part, it's not obvious unless you know sed. – domen Jan 26 '11 at 18:42
@domen: Good point, I added a brief description. – Matthew Crumley Jan 26 '11 at 21:21

linux - How can I add a line to a file in a shell script? - Stack Overflow

'via Blog this'

1 comment:

  1. Connie O'Dell - Dv, Eda, Jobseeking, Life,Whatever: How Can I Add A Line To A File In A Shell Script (With Sed)? - Stack Overflow >>>>> Download Now

    >>>>> Download Full

    Connie O'Dell - Dv, Eda, Jobseeking, Life,Whatever: How Can I Add A Line To A File In A Shell Script (With Sed)? - Stack Overflow >>>>> Download LINK

    >>>>> Download Now

    Connie O'Dell - Dv, Eda, Jobseeking, Life,Whatever: How Can I Add A Line To A File In A Shell Script (With Sed)? - Stack Overflow >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete