combining multiple rows in single row based on certain condition using awk or sed

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • samuel ray
    New Member
    • Jul 2011
    • 4

    combining multiple rows in single row based on certain condition using awk or sed

    Hi,

    I'm using AIX(ksh shell).

    > cat temp.txt

    "a","b",0
    "c",bc",0
    "a1","b1",0
    "cc","cb",1
    "cc","b2",1
    "bb","bc",2

    I want the output as:

    "a","b","c","bc ","a1","b1"
    "cc","cb","cc", "b2"
    "bb","bc"

    I want to combine multiple lines into single line where third column is same.

    Is it possible through paste,sed or awk commands?

    Regards,
    Sam
  • rski
    Recognized Expert Contributor
    • Dec 2006
    • 700

    #2
    If the lines you want to join are next to each other you can use that simple solution
    Code:
    awk  -F"," '
    BEGIN{num_old="";num_new=""}
    {if (num_old==""){num_old=$3;num_new=$3} else {num_new=$3} 
     if (num_old==num_new){printf $1 "," $2 ","} 
     if (num_old != num_new) {printf"\n";num_old=num_new;printf $1 "," $2 ","} 
    }
    END {printf "\n"} '  1.txt | sed 's/,$//g'
    If rows are not nex to each other then to use above solution you will have to sort that file by the last column or use some hash table to keep values.

    Comment

    Working...