将两列数据格式化为三列数据

时间:2016-04-27 05:43:16

标签: linux awk

我有一个包含两列数据的文件,如下所示 文件1:

1   
13  
1860    
168 1488.1
320 1566.5
476 1625.2
640 1684
840 1762.3
1092    1909.2
1460    2075.6
1824    2183.3
2400    2291
3260    2467.3
4340    2682.7
5468    2907.9
8188    3309.3
1   
13  
1940    
176 1503.1
348 1497.9
500 1586
640 1684
836 1821
1076    1938.5
1428    2075.6
1824    2183.3
2400    2291
3260    2467.3
4340    2682.7
5468    2907.9
8188    3309.3

输出应该符合要求 输出:

1860    168 1488.1
1860    320 1566.5
1860    476 1625.2
1860    640 1684
1860    840 1762.3
1860    1092    1909.2
1860    1460    2075.6
1860    1824    2183.3
1860    2400    2291
1860    3260    2467.3
1860    4340    2682.7
1860    5468    2907.9
1860    8188    3309.3
1940    176 1503.1
1940    348 1497.9
1940    500 1586
1940    640 1684
1940    836 1821
1940    1076    1938.5
1940    1428    2075.6
1940    1824    2183.3
1940    2400    2291
1940    3260    2467.3
1940    4340    2682.7
1940    5468    2907.9
1940    8188    3309.3

3 个答案:

答案 0 :(得分:2)

您可以使用此awk

awk 'NF==1{h=$1;next} {print h,$0}' file

输出:

1860 168 1488.1
1860 320 1566.5
1860 476 1625.2
1860 640 1684
1860 840 1762.3
1860 1092    1909.2
1860 1460    2075.6
1860 1824    2183.3
1860 2400    2291
1860 3260    2467.3
1860 4340    2682.7
1860 5468    2907.9
1860 8188    3309.3
1940 176 1503.1
1940 348 1497.9
1940 500 1586
1940 640 1684
1940 836 1821
1940 1076    1938.5
1940 1428    2075.6
1940 1824    2183.3
1940 2400    2291
1940 3260    2467.3
1940 4340    2682.7
1940 5468    2907.9
1940 8188    3309.3

答案 1 :(得分:0)

sed -rn ':a;/^[0-9]+[ \t]+$/h;/^[0-9]+[ \t]+[0-9]+/{!ba;G;s/(.*)\n(.*)/\2\1/;p}' file
1860    168 1488.1
1860    320 1566.5
1860    476 1625.2
1860    640 1684
1860    840 1762.3
1860    1092    1909.2
1860    1460    2075.6
1860    1824    2183.3
1860    2400    2291
1860    3260    2467.3
1860    4340    2682.7
1860    5468    2907.9
1860    8188    3309.3
1940    176 1503.1
1940    348 1497.9
1940    500 1586
1940    640 1684
1940    836 1821
1940    1076    1938.5
1940    1428    2075.6
1940    1824    2183.3
1940    2400    2291
1940    3260    2467.3
1940    4340    2682.7
1940    5468    2907.9
1940    8188    3309.3

答案 2 :(得分:0)

你可以试试这个:

$ awk -v prev='' 'NF==1{prev=$0;next}{$0=prev" "$0;print}' <filename>

<强>输出:

1860     168 1488.1
1860     320 1566.5
1860     476 1625.2
1860     640 1684
1860     840 1762.3
1860     1092    1909.2
1860     1460    2075.6
1860     1824    2183.3
1860     2400    2291
1860     3260    2467.3
1860     4340    2682.7
1860     5468    2907.9
1860     8188    3309.3
1940     176 1503.1
1940     348 1497.9
1940     500 1586
1940     640 1684
1940     836 1821
1940     1076    1938.5
1940     1428    2075.6
1940     1824    2183.3
1940     2400    2291
1940     3260    2467.3
1940     4340    2682.7
1940     5468    2907.9
1940     8188    3309.3