如何使用 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

相關內容