awk将一列拆分成多列

时间:2014-10-21 08:40:42

标签: bash command-line awk

如何使用awk根据列值将一个列数据拆分为多个列? 示例文件和所需的输出如下。我的bash版本是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

期望的输出:

$ 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

或者忘记空值如何在outputfile2中获得两列?

cat examplefile2
A
1
B
2
B
3
cat outputfile2
A   B
1   2
    B
    3

1 个答案:

答案 0 :(得分:0)

你可以得到它:

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

适用于任意数量的类(A,B,C ......)。

输出结果为:

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

如果您想将其作为列,请快速查看以下帖子: An efficient way to transpose a file in Bash

相关问题