使用awk解析文本文件

时间:2013-09-17 14:45:26

标签: linux awk

我希望使用awk解析空格分隔的输入文本文件。 列代码可以为每个组分配多个行。 我非常感谢任何帮助。

LOCATION
SHANNON

GROUP  NUM  SWITCH  CODE HEX
0      4     OFF    1    3
1      13    ON     2    4      
                    8
                    14

LOCATION
LOUTH

GROUP  NUM  SWITCH  CODE HEX 
0      1    OFF     1    4
1      2    ON      0    F
                    2

所需的输出文件

LOCATION GROUP  NUM  SWITCH  CODE HEX
SHANNON   0     4    OFF     1    3
SHANNON   1     13   ON      2    4  
SHANNON   1     13   ON      8    4  
SHANNON   1     13   ON      14   4 
LOUTH     0     1    OFF     1    4
LOUTH     1     2    ON      0    F
LOUTH     1     2    ON      2    F

1 个答案:

答案 0 :(得分:5)

#!/usr/bin/awk -f

BEGIN {
    # You can customize this to change your output layout based on your preference.
    format = "%-10s%-7s%-5s%-8s%-5s%-3s\n"
    printf format, "LOCATION", "GROUP", "NUM", "SWITCH", "CODE", "HEX"
}
++i==2{
    l = $1
}
i>4{
    if (/^[[:blank:]]*$/) {
        i = 0
    } else if (NF > 1) {
        printf format, l, $1, $2, $3, $4, $5
        p1=$1; p2=$2; p3=$3; p5=$5
    } else {

        printf format, l, p1, p2, p3, $1, p5
    }
}

使用以下命令运行:

awk -f script.awk file

输出:

LOCATION  GROUP  NUM  SWITCH  CODE HEX
SHANNON   0      4    OFF     1    3  
SHANNON   1      13   ON      2    4  
SHANNON   1      13   ON      8    4  
SHANNON   1      13   ON      14   4  
LOUTH     0      1    OFF     1    4  
LOUTH     1      2    ON      0    F  
LOUTH     1      2    ON      2    F