如何使用 awk 格式化列?

如何使用 awk 格式化列?

文件 rectData.ssv 包含:

rectangle1;1;2
rectangle2;1;10
rect4;10;10

如何更改以下命令以对齐列:

$ awk -F ";" '{ print "area of", $1,":", $2 * $3}' rectData.ssv
area of rectangle1 : 2
area of rectangle2 : 10
area of rect4 : 100

预期输出如下:

area of rectangle1:   2
area of rectangle2:   10
area of rect4:        100

(2、10 和 100 左对齐)

或者:

area of rectangle1:    2
area of rectangle2:   10
area of rect4:       100

(2、10 和 100 右对齐)


另外,如何在末尾添加一行总计(2、10、100 和 112 右对齐):

area of rectangle1:    2
area of rectangle2:   10
area of rect4:       100
TOTAL AREA:          112

答案1

尝试对您的尝试进行以下调整:

$ awk -F ";" '
        {TOT += $2 * $3
         printf "area of %s: %*d\n", $1, 14-length($1), $2 * $3
        }
END     {printf "TOTAL AREA: %*d\n", 12, TOT
        }
' file
area of rectangle1:    2
area of rectangle2:   10
area of rect4:       100
TOTAL AREA:          112

答案2

$ awk -F ';' -v OFS='\t' '
    { tot+=prod=$2*$3; print "area of " $1 ":", prod }
    END { print "TOTAL AREA:", tot+0 }
' file | column -s$'\t' -t
area of rectangle1:  2
area of rectangle2:  10
area of rect4:       100
TOTAL AREA:          112

相关内容