-3

How can split one column data into multiple columns based on column values using awk? Example file and desired output is below. My bash version is 3.2.52(1).

$ cat examplefile
A
1
B
2
B
3
C
10
C
11
C
13
A
4
B
5
B
6
B
7
C
14

Desired output:

$ cat outputfile
A        B      C
1        2      10
null     B      C
null     3      11
null    null    C
null    null    13
A       B       C
4       5       14
null    B       null
null    6       null
null    B       null
null    7       null

Or forget about null values How can I obtain two columns as in the outputfile2?

cat examplefile2
A
1
B
2
B
3
cat outputfile2
A   B
1   2
    B
    3
Jongware
  • 22,200
  • 8
  • 54
  • 100

1 Answers1

1

You can get it:

awk 'BEGIN{l=1;ll="";} {if (l) {ll=$0;l=0;} else {if (length(a[ll])>0) {a[ll]=a[ll]","ll","$0;} else {a[ll]=ll","$0;}l=1;}} END{for (k in a){print a[k];}}' examplefile

It works for any number of classes (A,B,C...).

The output is:

A,1,A,4
B,2,B,3,B,5,B,6,B,7
C,10,C,11,C,13,C,14

If you want it as columns, just have a quick look to the following post: An efficient way to transpose a file in Bash

Community
  • 1
  • 1
arutaku
  • 5,937
  • 1
  • 24
  • 38