I have a file that I need to reformat so that every time I match a certain string in the first column it prints to the string as the heading and under the sting it prints the remaining entries on the line that matched the string.
For example, I need to reformat this
xxx : yyy zzz
11 : 111 222 xxx
xyz : abc def
xxx : aaa bbb
11 : 555 333 yy
xyz : abc xyz
To look like this with xxx, 11 and xyz as the headers/titles for each column.
xxx 11 xyz
yyy zzz 111 222 xxx abc def
aaa bbb 555 333 yy abc xyz
Yoda
December 18, 2012, 11:40am
2
awk -F: ' BEGIN {
printf "%-15s%-15s%-15s\n", "xxx", "11", "xyz" } {
if(NR%3==0) {
sub(" ","",$2);
printf "%-15s\n", $2;
}
else {
sub(" ","",$2);
printf "%-15s", $2;
}
} ' infile
If you were looking for something that self adjusts based on the column headings and data to be displayed, you could try something like:
awk -F" : " '
# c[heading] = # of values accumulted for heading
# h[heading] = heading_field
# hc = # of headings
# ho[heading_field] = heading
# r = # of rows to be printed (not counting headings)
# v[heading,c[heading]] = value to be printed in row c[heading] under heading
# w[heading_field] = widest field data for heading_field
{ v[$1,++c[$1]] = $2
if(!($1 in h)) {
ho[++hc] = $1
h[$1] = hc
w[hc] = length($1)
}
if(w[h[$1]] < length($2)) w[h[$1]] = length($2)
if(c[$1] > r) r = c[$1]$1, c[$1], $1, h[$1], hc, ho[hc], r, $1, $1, c[$1], v[$1,c[$1]], h[$1], w[h[$1]])}
END { for(i = 1; i < hc; i++)
printf("%-*.*s", w + 3, w + 3, ho)
printf("%-s\n", ho[hc]);
for(j = 1; j <= r; j++) {
for(i = 1; i < hc; i++)
printf("%-*.*s", w + 3, w + 3, v[ho, j]);
printf("%-s\n", v[ho[hc], j]);
}
}' file
With the sample input file given in the 1st message in this thread, it produces the output:
xxx 11 xyz
yyy zzz 111 222 xxx abc def
aaa bbb 555 333 yy abc xyz
rdrtx1
December 18, 2012, 9:00pm
4
try also:
awk -F" *: *" '!a[$1]++ {b[c++]=$1;}
{cn=ca[$1]++; e[$1]=$1; d[$1, a[$1]-1]=$2;}
END {
for (i=0; i<c; i++) {printf("%-20s", b)}; print "";
for (j=0; j<=cn; j++) {for (i=0; i<c; i++) {printf("%-20s",d[e[b],j])} print ""; }
}' infile
Thank you very much guys. These posts have been extremely helpful. They all work!