awksedxen

merge a command's output with another's last field


xen list; xen uptime , want to merge both command o/p to single..

hostname1-$ xen list; xen uptime 
Name                                        ID   Mem VCPUs      State   Time(s)
Domain-0                                     0  1917    24     r----- 6651158.5
aa                                         1  8192     4     -b---- 5826608.0
bb                                       9 12288     4     r----- 192566.9
Name                                ID Uptime 
Domain-0                             0 176 days, 10:54:22
aa                                  1 176 days, 10:15:33
bb                               9 5 days,  0:29:35

I tried with multiple ways to merge using awk,grep & sed but not getting below o/p as expected

Name                                        ID   Mem VCPUs      State   Time(s)  uptime
Domain-0                                     0  1917    24     r----- 6651158.5.  176 days,
aa                                         1  8192     4     -b---- 5826608.0.    176 days,
bb                                       9 12288     4     r----- 192566.9.       5 days

I only want uptime field in the 2nd command o/p..
could some help me with this please


Solution

  • Could you please try following. Written and tested with shown samples.

    awk 'FNR==NR{if(FNR==1){a[$1]=$NF;next};match($0,/[0-9]+ days/);a[$1]=substr($0,RSTART,RLENGTH);next} {print $0,a[$1]}' <(xen uptime) <(xen list)
    

    OR adding a non-one liner form of solution:

    awk '
    FNR==NR{
      if(FNR==1){
        a[$1]=$NF
        next
      }
      match($0,/[0-9]+ days/)
      a[$1]=substr($0,RSTART,RLENGTH)
      next
    }
    {
      print $0,a[$1]
    }' <(xen uptime) <(xen list)
    


    EDIT: As per OP in case someone wants don't want to print State and Time values then try following.

    awk '
    FNR==NR{
      if(FNR==1){
        a[$1]=$NF
        next
      }
      match($0,/[0-9]+ days/)
      a[$1]=substr($0,RSTART,RLENGTH)
      next
    }
    {
      $NF=$(NF-1)=""
      sub(/ +$/,"")
      print $0,a[$1]
    }' <(xen uptime) <(xen list)