This answer builds on Ralph Rönnquist’s answer, but
- assumes that the columns should be output in user-specified order
rather than alphabetical order by heading, and
- allows the data values to be multi-word.
Like Ralph’s answer, this assumes that the titles are separated from the data
by a space and not a colon.
In order to implement goal #1,
it requires that the input begin with a stanza containing all the titles
(with no accompanying data) in the desired order.
BEGIN { i = 0; j= 0; }
$1 != "" { if (i==0) C[++j] = $1; else { label = $1; $1 = ""; X[label,i] = $0; } next; }
{ i++; }
END {
for ( k in C ) printf " %8s\t", C[k];
printf "\n";
for ( j = 1; j <= i; j++ ) {
for ( k in C ) printf "%8s\t", X[C[k],j];
printf "\n";
}
}
Note that i
is initialized to 0
,
and that the i==0
case is handled specially —
only the title is captured
(since that’s the only thing that should be there),
and the titles are stored in the C
array
indexed by an increasing integer (j
)
rather than by the value of the title itself.
Otherwise, we capture data.
$1 = "";
erases the first field in the line
and rebuilds $0
as the concatenation of all the other fields.
(This loses multiple spaces between fields;
that can be corrected with a little bit of work.)
We save the $1
value in the label
variable
so we can use it as an index into the data array, X
.
So, for example, this input:
name
address
phone
height
weight
name John Lennon
phone 123
height 6' 1"
weight 180
name Sir Paul M.
address Liverpool
weight 175
name George
address 42 Main St.
height 71"
weight 185 lbs
name Ringo Starr
address Penny Lane
phone 456 789
yields this output:
name address phone height weight
John Lennon 123 6' 1" 180
Sir Paul M. Liverpool 175
George 42 Main St. 71" 185 lbs
Ringo Starr Penny Lane 456 789
The columns will be off if any value is 15 characters long or longer.
This can also be improved.
Had a basic question though, what is the way I can execute the code? Save it as .awk first and then call it with the argument as my file with -f option?
P.S. (This is my first day with awk code hence the basic query) :)
– user157638 Feb 22 '16 at 05:50title1
,title2
,title3
,title4
, andtitle5
, I suspect that they might be something likename
,address
,phone
,height
, andweight
), and (2) the data values are all just one word. – Scott - Слава Україні Feb 22 '16 at 06:11