2

I have the below data in a file:

col1 col2 col3 subcol1 subcol2 subcol3
               subcol4 subcol5 subcol6
          col4 subcol7 subcol8 subcol9
               subcol10 subcol11 subcol2

The data is delimited by spaces. No tabs I want to convert this data as shown below:

-------------------------------------------------------
col1  | col2 | col3  |   subcol1  | subcol2 | subcol13     
                       --------------------------------
      |      |       |   subcol4  | subcol5 | subcol6
              -----------------------------------------         
      |      | col4  |   subcol7  | subcol8 | subcol9     
                       --------------------------------
      |      |       |   subcol10 | subcol11| subcol12  
-------------------------------------------------------

How can I accomplish this?

Edited

I have tried below command

sed -r -e 's/ {5}/\t/g' -e 's/ /\t/g' file.in | sed -e 's/\t/_|/g'|  column -t -s '_'

It produces

col1  |col2 |col3  |subcol1  |subcol2  |subcol13     
      |     |      |subcol4  |subcol5  |subcol6
      |     |col4  |subcol7  |subcol8  |subcol9     
      |     |      |subcol10 |subcol11 |subcol12    

It just needs that line to fill this

4
  • Is the indentation of the input data done with spaces or tabs? – Kusalananda Aug 28 '17 at 19:02
  • input data is delimited by space only – wazza Aug 28 '17 at 19:08
  • 1
    If anyone wants to work on this, assuming spaces only, this is how you make it tab-delimited with GNU sed: sed -r -e 's/ {5}/\t/g' -e 's/ /\t/g' file.in – Kusalananda Aug 28 '17 at 19:16
  • sorry its my mistake now again edited – wazza Aug 28 '17 at 19:16
2

I ended-up with following awk script.

awk '{gsub(/ {1,5}/,"\t|")}1' infile.txt | \
awk -F'|' 'NR>1{for(i=1;i<=NF;i++) if ($i=="\t") c++;
           printf("%*s",(c*8),"\t-");
           for (fill=1;fill<=length($0)+c;fill++)printf "-";
           printf("\n%s\n",$0);c=0;next} {print $0}'

The output is:

col1    |col2   |col3   |subcol1        |subcol2        |subcol3
                        -----------------------------------     
        |       |       |subcol4        |subcol5        |subcol6
                --------------------------------------          
        |       |col4   |subcol7        |subcol8        |subcol9
                        -------------------------------------   
        |       |       |subcol10       |subcol11       |subcol2
3
  • it is creating the lines but they are not even as I said in the expected output – wazza Aug 29 '17 at 5:51
  • can u explain ur code so that I can extend it – wazza Sep 6 '17 at 14:16
  • I will update my answer with your full expectation as well as explanation : ) – αғsнιη Sep 6 '17 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.