Here are three different awk scripts to do this making different assumptions about the number of columns/row, and width of columns. If you input data is always less that 8 output columns per input line and you always have three input lines per output row, the 1st script is very simple.
If your input data has input lines that vary in length, but there are always three input lines per output row, the 2nd awk script below adjusts the output to match input field widths.
If you have a variable number of input lines per output row but the column 1 input line data always ends with a colon, the 3rd awk script below will adjust the number of rows and column widths based on the input file contents.
Here are the three awk scripts:
echo 'Following assumes 3 lines/row, tab separator:'
awk '{printf("%s%s", $0, NR % 3 ? "\t" : "\n")}' input
echo
echo 'Following assumes 3 lines/row, field width based on input:'
awk '
{ o[int((NR + 2)/3),++c] = $0
if(length($0) > w[c]) w[c] = length($0)
if(c == 3) c = 0
}
END { fmt = sprintf("%%-%ds%%-%ds%%s\n", w[1] + 2, w[2] + 2)
#printf("fmt=%s\n", fmt)
for(i = 1; i <= NR / 3; i++)
printf(fmt, o[i,1], o[i,2], o[i,3])
}' input
echo
echo 'Following assumes Column 1 data ends with ":", field width based on input:'
awk '
/:$/ { r++
if(c > mc) mc = c
c = 0
}
{ o[r,++c] = $0
if(length($0) > w[c]) w[c] = length($0)
}
END { for(i = 1; i <= r; i++) {
for(j = 1; j < mc; j++)
printf("%-*s", w[j] + 2, o[i, j])
printf("%s\n", o[i, mc])
}
}' input
When these three scripts are given the a file named input
containing:
INT1:
STR1
STR2
EXT1:
STR1
STR2
INT2:
STR1
STR2
Longer Column 1:
Column2
column three
column four
column 5
c6
2nd C1:
2nd C2
2nd C3
2nd C4
2nd C5
Second Column 6
the output produced is:
Following assumes 3 lines/row, tab separator:
INT1: STR1 STR2
EXT1: STR1 STR2
INT2: STR1 STR2
Longer Column 1: Column2 column three
column four column 5 c6
2nd C1: 2nd C2 2nd C3
2nd C4 2nd C5 Second Column 6
Following assumes 3 lines/row, field width based on input:
INT1: STR1 STR2
EXT1: STR1 STR2
INT2: STR1 STR2
Longer Column 1: Column2 column three
column four column 5 c6
2nd C1: 2nd C2 2nd C3
2nd C4 2nd C5 Second Column 6
Following assumes Column 1 data ends with ":", field width based on input:
INT1: STR1 STR2
EXT1: STR1 STR2
INT2: STR1 STR2
Longer Column 1: Column2 column three column four column 5 c6
2nd C1: 2nd C2 2nd C3 2nd C4 2nd C5 Second Column 6
As always, if you're using a Solaris/Sun OS system, use /usr/xpg4/bin/awk
or nawk
instead of awk
.