Search code examples
csvawkzshinformixkeyvaluepair

How do I convert key value paired list into table with columns using AWK?


I need to convert a dataset from a key value paired list (informix dbaccess output) into a columned csv. I'm fairly certain this can be done easily with awk or sed.

UPDATE The solution needs to be a single line response. I am using NSH (which is based on ZSH). So some of the typical "bashy" commands will not work.

Here is my data sample set:

part_no            100000001
date_part          2010-10-13 12:12:12
history_code       ABCD
user_id            rsmith
other_information   note: Monday, December 10
pool_no            101011777

part_no            100000002
date_part          2010-10-21 12:12:12
history_code       GHIJ
user_id            jsmith
other_information
pool_no            101011888

part_no            100000002
date_part          2010-10-27 12:12:12
history_code       LMNO
user_id            fevers
other_information   [Mail]
pool_no            101011999

part_no            100000003
date_part          2010-11-13 12:12:12
history_code       QXRT
user_id            sjohnson
other_information   note: Tuesday, August 31
pool_no            101011111

I need it to look like this:

part_no,date_part,history_code,user_id,other_information,pool_no
100000001,10/13/2010 12:12:12,ABCD,rsmith,note: Monday, December 10,101011777
100000002,10/21/2010 12:12:12,GHIJ,jsmith,,101011888
100000002,10/27/2010 12:12:12,LMNO,fevers,[Mail],101011999
100000003,11/13/2010 12:12:12,QXRT,sjohnson,note: Tuesday, August 31,101011111

Solution

  • Your question isn't clear but this MAY be what you're looking for:

    $ cat tst.awk
    BEGIN { RS=""; FS="\n"; OFS=","; ofmt="\"%s\"%s" }
    {
       for (i=1; i<=NF; i++) {
           tag = val = $i
           sub(/[[:space:]].*/,"",tag)
           sub(/[^[:space:]]+[[:space:]]+/,"",val)
           tags[i] = tag
           vals[i] = val
        }
    }
    NR==1 {
        for (i=1; i<=NF; i++) {
            printf ofmt, tags[i], (i<NF ? OFS : ORS)
        }
    }
    {
        for (i=1; i<=NF; i++) {
            printf ofmt, vals[i], (i<NF ? OFS : ORS)
        }
    }
    
    $ awk -f tst.awk file
    "part_no","date_part","history_code","user_id","other_information","pool_no"
    "100000001","2010-10-13 12:12:12","ABCD","rsmith","note: Monday, December 10","101011777"
    "100000002","2010-10-21 12:12:12","GHIJ","jsmith","other_information","101011888"
    "100000002","2010-10-27 12:12:12","LMNO","fevers","[Mail]","101011999"
    "100000003","2010-11-13 12:12:12","QXRT","sjohnson","note: Tuesday, August 31","101011111"