如何在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
答案 0 :(得分:0)
假设您的样本数据中存在拼写错误(主机1实际上是host5 1)。您可以使用 GNU 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