如何在不删除分隔符的情况下对齐列中的文本(居中)?

时间:2015-10-10 09:03:54

标签: bash shell

我想调整以列为中心的源代码......

来源:

IP | ASN | Prefix        | AS Name           | CN | Domain    | ISP
109.228.12.96 | 8560 | 109.228.0.0/18 | ONEANDONE | DE | fasthosts.com | Fast Hosts LTD

目标:

IP            | ASN  | Prefix         | AS Name   | CN | Domain        | ISP
109.228.12.96 | 8560 | 109.228.0.0/18 | ONEANDONE | DE | fasthosts.com | Fast Hosts LTD

我在命令列中尝试了不同的东西......但我内部有双重空格:

cat Source.txt | sed 's/ *| */@| /g' | column -s '@' -t

IP             | ASN   | Prefix          | AS Name    | CN  | Domain         | ISP
109.228.12.96  | 8560  | 109.228.0.0/18  | ONEANDONE  | DE  | fasthosts.com  | Fast Hosts LTD

有没有办法在不删除分隔符的情况下使用列...或其他解决方案?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

你也可以用awk做所有事情。将程序保存到 pr.awk 并运行

awk -f pr.awk input.dat

BEGIN {
    FS = "|"

    ARGV[2] = "pass=2"  # a trick to read file two times
    ARGV[3] = ARGV[1]
    ARGC=4
    pass = 1
}

function trim(s) {
    sub(/^[[:space:]]+/, "", s) # remove leading
    sub(/[[:space:]]+$/, "", s) # and trailing whitespaces
    return s
}

pass == 1 {
    for (i=1; i<=NF; i++) {
       field = trim($i)
       len   = length(field)
       w[i] = len>w[i] ? len : w[i] # find the maximum width
    }
}

pass == 2 {
    line = ""
    for (i=1; i<=NF; i++) {
       field = trim($i)
       s   = i==NF ? field : sprintf("%-" w[i] "s", field)
       sep = i==1  ? ""    : " | "
       line = line sep s
    }
    print line
}

答案 1 :(得分:0)

列有输入sepatator -s并输出seperator -o 所以电话就像是

cat file |列-t -s&#39; |&#39; -o&#39; |&#39;