Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unstack columns

Status
Not open for further replies.

KingVodka

Technical User
Dec 15, 2003
5
NL
Is there any possibility to unstack columns in awk using a grouping column?

Like this:
a 1
b 2
c 3
a 4
b 5
c 6

Unstacking above data should yield
a b c
1 2 3
4 5 6
 
Something like this ?
Code:
rm -f out.*
awk '
!($1 in a){++a[$1];print $1 >("out."$1)}
{print $2 >("out."$1)}
' /path/to/input | paste -d" " out.*

Hope This Help
PH.
 
Isn't there a mors subtile way of writing that. Something which I can use easily like this: gawk -f *.awk input file > output
 
Is my solution working or not ?
If you don't like the shell piping you can do the paste in the END section either manually or with the system function.

Hope This Help
PH.
 
I think this is the same question as another recent post, just re-phrased. Here's my solution....
[tt]
#!/usr/bin/awk -f
{
if ($1 in col) {
cnt=++col[$1];
} else {
col[$1]=1;
row[0]=row[0] " " $1;
cnt=1;
};
row[cnt]=row[cnt] " " $2;
if (cnt>max)
max=cnt;
} END {
for(x=0;x<=max;x++)
print row[x]
}
[/tt]
Tested...
[tt]
a b c
1 2 3
4 5 6
[/tt]
More testing...
[tt]
0 10 20 30 40
99 87 53 64 82
105 92 84 78 89
[/tt]
 
PHV, your solution works fine but without the pipe of the paste command.

rm -f out.*
awk '
!($1 in a){++a[$1];print $1 >(&quot;out.&quot;$1)}
{print $2 >(&quot;out.&quot;$1)}
' /path/to/input
paste -d&quot; &quot; out.*



Jean Pierre.
 
aigles, good catch for the unnecessary pipe. But in my SCO box they doesn't matter...
 
Ygor,

Is there a possibility to enlarge the space between the
columns. Now I have some columsn which overlap like this:

0.00E+00 1.5000E+01 6.0000 E+01 7.5000E+
1.51E+01 2.55E+00 -1.13E+00
1.59E+01 5.17E+00 -5.23E-01
2.77E+01 1.68E+01 1.82E+01


Is there a solution to solve above problem?


 
You can impose your own formatting with sprintf. The first one is used to format the heading, the second for the data ...
[tt]
#!/usr/bin/awk -f
{
if ($1 in col) {
cnt=++col[$1];
} else {
col[$1]=1;
row[0]=row[0] sprintf(&quot; %10.3f&quot;,$1);
cnt=1;
};
row[cnt]=row[cnt] sprintf(&quot; %10.3f&quot;,$2);
if (cnt>max)
max=cnt;
} END {
for(x=0;x<=max;x++)
print row[x]
}
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top