awk - script help: column to row format of data allignment?

Experts Good day,

I have the following data, file1


BRAAGRP1
A2X
B2X
C2X
D2X

BRBGRP12
A3X
B3X
Z10
D09

BRC1GRP2
LO01
LO02
LO03
LO09

BR11GR112
NN01
NN02
M001
M002

I am trying to get it into this format & horizontally :

BRAAGRP1 	BRBGRP12	BRC1GRP2	BR11GR12
A2X       	A3X          	LO01        	NN01
B2X         	B3X          	LO02        	NN02
C2X         	Z10          	LO03        	M001
D2X        	D09          	LO09        	M002

Can any one advise with good awk or other unix script or code,
Thanks a lot.

Try:

awk '/^$/{i=0}!/^$/{i++;x=sprintf ("%-17s", $0);a=a""x}END{for (j=1;j<=i;j++) print a[j]}' file
1 Like

burstus1 , Thanks! This is a great code and very interesting , I am not able to understand fully ,
I got sprint %-17s , to get the space, then what is the array function and till end couldnt understand. Appreciate if you can explain little bit. Thanks again for the help.

Reveri.

An equivalent awk script with comments is:

awk '
/^$/{   i=0     # Set output row counter to 0 when you find an empty line.
}
!/^$/{  i++     # Increment output row counter when you find a line with data.
        x=sprintf ("%-17s", $0) # Set x to current line expanded to length 17
                                # by adding trailing spaces.
        a=a x     # Add expanded current line to the end of row i data.
}
END{    for(j=1;j<=i;j++) print a[j]    # Print data for each accumulated row.
}' file1        # Read input data from a file named file1.
2 Likes

Print the data in some different format.

awk '$1=$1' FS='\n' OFS='\t' RS=
BRAAGRP1        A2X     B2X     C2X     D2X
BRBGRP12        A3X     B3X     Z10     D09
BRC1GRP2        LO01    LO02    LO03    LO09
BR11GR112       NN01    NN02    M001    M002
1 Like