-3

如何在 awk 中格式化输出?或 ksh 打印命令

我有一个文件

bash-3.2# cat filename
host    1
host1   2       1
host2   3       2       1
host3   1       2
host4   3       2       1

希望像下面一样对齐输出。

host1           2       1
host2   3       2       1
host3           2       1
host4   3       2       1
host5                   1
4

1 回答 1

0

假设您的示例数据中有错字(host 1 实际上是 host5 1)。你可以这样做GNU awk

script.awk 的内容:

NR==FNR {
    for (c = 2 ; c <= NF ; c++) {
        high = (high > $c) ? high : $c
    }
    next
}
{
    delete a
    delete b
    n = p = shift = 0
    printf "%s\t",$1
    for (i = 2 ; i <= NF ; i++) {
        a[$i]
    }
    n = asorti(a,b)
    for (x = n ; x > 0 ; x--) {
        if (b[x] < high) { shift = high - b[x] }
            while (++p <= shift) {
            printf "\t"
        }
        printf "%s\t", b[x]
        }
    print ""
}

测试:

$ cat file
host1   2   1
host2   3   2   1
host3   1   2
host4   3   2   1
host5   1

$ gawk -f script.awk file file
host1       2   1   
host2   3   2   1   
host3       2   1   
host4   3   2   1   
host5           1   

$ cat file2
host1   2   1
host2   3   2   1
host3   1   2
host4   3   5   1
host5   1

$ gawk -f script.awk file2 file2
host1               2   1   
host2           3   2   1   
host3               2   1   
host4   5       3       1   
host5                   1   
于 2013-06-22T04:58:35.410 回答