Re: using sed to add text to csv file

Tim Chase <[email protected]>
Newsgroups gmane.editors.sed.user
Message-ID <[email protected]>
On 05/04/12 08:44, Gary Carr wrote:
> 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&

While perhaps out of place on a sed mailing list, since it looks
like you're trying to construct an HTML GET query-string from the
file, I'd be tempted to use a quickie Python to provide more robust
handling of CSV files and the escaping of problematic characters
(such as spaces or possible ampersands like an address of "1234
Brighton & Mills Way" in values).  In all its glory, I'd try

=========urlify.py=====================
import csv
import urllib
for line in csv.DictReader(file('data.csv')):
    print(urllib.urlencode(line.items()))
=======================================

and then just execute it with

  bash$ python urlify.py > output.txt

It has the slight issue that the order may come out differently
(dictionaries are inherently unsorted) but that shouldn't matter in
the composition of a GET request's parameters.  If you want a
version that preserves order, it's a little longer:

========urlify2.py======================
import csv
import urllib
f = file('data.csv')
try:
    r = csv.reader(f)
    headers = r.next()
    # headers = map(lambda s: s.lower(), headers)
    for line in r:
        print(urllib.urlencode(zip(headers, line)))
finally:
    f.close()
========================================

Either way, you might have a lot less headache if your eventual goal
is to make valid URL strings.  It will use whatever the headers are
as the variables, so you can adjust those accordingly (if you just
want to lower-case them, you can uncomment the one line in the 2nd
example; I did notice that your example output used completely
different headers for several fields which may impact how you do
what you want)

-tim
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.