Search code examples
linuxawksedmergerow

linux merge rows if Columns less than X


I need you support in creating the output. I have output as

1  ABC  STATUS       
   7    PROHIBITED   
   8    PROHIBITED   
2  CDE  STATUS       
   7    PROHIBITED   
   8    PROHIBITED   
3  FGH  STATUS       
   142  PROHIBITED   
2  HIJ  STATUS       
   7    PROHIBITED   

I am trying to achieve as

`1  ABC  STATUS      7      PROHIBITED   8      PROHIBITED   
2  CDE  STATUS       7    PROHIBITED   8    PROHIBITED   
3  FGH  STATUS       142  PROHIBITED   
2  HIJ  STATUS       7      PROHIBITED

OR Either below where every first and second column is filled in below empty gaps.

`1  ABC  STATUS      
1  ABC   7      PROHIBITED   
1  ABC   8      PROHIBITED   
2  CDE  STATUS       
2  CDE   7    PROHIBITED   
2  CDE  8    PROHIBITED   
3  FGH  STATUS       
3  FGH   142  PROHIBITED   
2  HIJ  STATUS       
2  HIJ    7     PROHIBITED   
2  HIJ    8     PROHIBITED   `

so far I have tried to achieve this in one single row with

cat file | paste -sd'\t\n'

but it is not showing the result as expected. it would be appreciated if any one can provide me with guidance as to how to achieve


Solution

  • One awk idea for generating the first set of output:

    awk '
        { if (NF==3)
             printf "%s%s",(NR>1 ? "\n" : ""),$0        # if not 1st row of input then prefix the output with "\n" (to terminate previous line of output)
          else      
             printf "%s",$0
        }
    END {print ""}                                      # terminate last line of output
    ' file
    

    This generates:

    1  ABC  STATUS   7    PROHIBITED   8    PROHIBITED
    2  CDE  STATUS   7    PROHIBITED   8    PROHIBITED
    3  FGH  STATUS   142  PROHIBITED
    2  HIJ  STATUS   7    PROHIBITED   8    PROHIBITED