awk只将特定行转置为多列

时间:2018-03-19 21:38:40

标签: awk formatting rows lines

有人知道如何在文件中转换这些行输入吗?

invStatus: ONLINE
System: 55
StatFail: 0
invState: 0 Unknown
invFailReason: None
invBase: SYS-MG5-L359-XO1-TRAFFIC STAT 5: TRAF2
invFlag: 0xeee5 SEMAN PRESENT STATUS H_DOWN BASE LOGIC_ONLINE DEX EPASUS INDEX ACK
dexIn: 0
dexIO: 0
badTrans: 0
badSys: 0
io_IN: 0
io_OUT: 0
Tr_in: 0
Tr_out: 0

进入类似的输出:

invBase:   SYS-MG5-L359-XO1-TRAFFIC STAT 5: TRAF2
invFlag:   0xeee5 SEMAN PRESENT STATUS H_DOWN BASE LOGIC_ONLINE DEX EPASUS INDEX ACK
invStatus: ONLINE   System:     55    StatFail:   0     invState:    0 Unknown  invFailReason: None   
dexIn:        0     dexIO:       0    badTrans    0     badSys:      0
io_IN:        0     io_OUT:      0    Tr_in:      0     Tr_out:      0

我在开始时第一次尝试在每一行的末尾添加";"然后加入多行>然后基于字符串拆分它们但仍然变得混乱输出

我现在处于格式化阶段:

cat port | sed 's/$/;/g' | awk 'ORS=/;$/?" ":"\n"'

1 个答案:

答案 0 :(得分:0)

我从这个开始

awk -F: '
    {data[$1] = $0}
    END {
        OFS="\t"
        print data["invBase"]
        print data["invFlag"]
        print data["invStatus"], data["System"], data["StatFail"], data["invState"], data["invFailReason"]
        print data["dexIn"], data["dexIO"], data["badTrans"], data["badSys"]
        print data["io_IN"], data["io_OUT"], data["Tr_in"], data["Tr_out"]
    }
' file
invBase: SYS-MG5-L359-XO1-TRAFFIC STAT 5: TRAF2
invFlag: 0xeee5 SEMAN PRESENT STATUS H_DOWN BASE LOGIC_ONLINE DEX EPASUS INDEX ACK
invStatus: ONLINE       System: 55      StatFail: 0     invState: 0 Unknown     invFailReason: None
dexIn: 0        dexIO: 0        badTrans: 0     badSys: 0
io_IN: 0        io_OUT: 0       Tr_in: 0        Tr_out: 0

然后,为了使它变得漂亮,首先要存储行长度,然后使用其中一些长度将print语句更改为printf语句。

仔细查看该文件可以发现,除了3行外,它们是顺序的,可以粘贴到4列中:

awk -F: '
    $1 == "invBase" || $1 == "invFlag" {print; next}
    $1 == "invStatus" {invStatus = $0; next}
    {line[n++] = $0}
    END {
        printf invStatus "\t"
        paste = "paste - - - -"
        for (i=0; i<n; i++) {print line[i] | paste}
        close(paste)
    }
' file

提供与上面相同的输出。