Re: using sed to add text to csv file

Cameron Simpson <[email protected]>
Newsgroups gmane.editors.sed.user
Message-ID <[email protected]>
On 04May2012 09:44, Gary Carr <[email protected]> wrote:
| Hello to all. This is my first post to this mailing list. 
| 
| I have a CSV file with thousands of lines that is laid out like such.
| 
| First,Last,Address,City,St,Zip,email,phone,dob,optindate,ipaddress,url
| Joey,Smith,12036 Address Lane,Beverly Hills,CA,90210,[email protected],2484865073,02/08/1962,4/2/2008 19:04:20,192.69.141.22,http://www.url.com/
| 
| I am trying to add text to the beginning of each table then change each line to the following
| 
| firstname=Joey&lastname=Smith&address=12036 Address Lane&
| 
| So basicallly I am trying to add the "headername=" text to the beginning
| of each row then replace the , with a & I know how to replace the comma
| I just can not figure out how to add the header text to the beginning
| of each line.

I would use awk for this, myself. Untested example:

  awk -v 'FS=,' -v 'OFS=&' 'NR > 1 { print "firstname=" $1, "lastname=" $2, }

extended tediously for all the fields. That's all on one line, should
your mailer fold things up.

In sed you could either write a horrendous regexp like this:

  s/^\([^,]*\),\([^,]*\),.../firstname=\1&lastname=\2&.../

extending it for all the columns (which will be hard to debug when you
have a small typo) or you could work progressively with a multiline sed
script, relying on there being no commas in the data:

  s/^\([^,]*\),/firstname=\1&/
  s/\&\([^,]*\),/lastname=\1&/
  s/\&\([^,]*\),/address=\1&/

extending as needed. That way the unadjusted columns in the output will
point the way to typos in the script.

Cheers,
-- 
Cameron Simpson <[email protected]> DoD#743
http://www.cskk.ezoshosting.com/cs/

Weakness is a better teacher than strength.  Weakness must learn to
understand the obstacles that strength brushes aside. - Mason Cooley
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.