Linux 使用awk打印列及其标题
我正在尝试为表中的列设置标题,我使用了以下代码:Linux 使用awk打印列及其标题,linux,unix,awk,Linux,Unix,Awk,我正在尝试为表中的列设置标题,我使用了以下代码: $ awk 'BEGIN {print "Name\tDescription\tType\tPrice";} > {print $1,"\t",$2,"\t",$3,"\t",$4,"\t",$NF;} > END{print "Report Generated\n--------------"; > }' t
$ awk 'BEGIN {print "Name\tDescription\tType\tPrice";}
> {print $1,"\t",$2,"\t",$3,"\t",$4,"\t",$NF;}
> END{print "Report Generated\n--------------";
> }' toys | column -s '/' -t
我尝试过这段代码,但不了解sytax及其实现:
$ awk 'BEGIN {print "Name\tDescription\tType\tPrice";}
> {printf "%-24s %s\n", $1,$2,$3,$NF;}
> }' toys
我想要的数据和结果:
该表包括:
Mini car Kids under 5 Wireless 2000
Barbie Kids 6 - 12 Electronic 3000
Horse Kids 6 -8 Electronic 4000
Gitar 12 -16 ELectronic 45000
当我打印上述命令时,它会给我以下输出:
Name Description Type Price
Mini car Kids under 5 Wireless 2000
Barbie Kids 6 - 12 Electronic 3000
Horse Kids 6 -8 Electronic 4000
Gitar 12 -16 ELectronic 45000
我希望有人帮我把它们打印成这样:
Name Description Type Price
Mini car Kids under 5 Wireless 2000
Barbie Kids 6 - 12 Electronic 3000
Horse Kids 6 -8 Electronic 4000
Gitar 12 -16 ELectronic 45000
要打印的每个值都需要一个格式化运算符。由于要打印4列,因此需要4个格式化运算符来指定每列的宽度
$ awk 'BEGIN {printf("%-10s %-15s %-10s %s\n", "Name", "Description", "Type", "Price");}
> {printf("%-10s %-15s %-10s %d\n", $1, $2, $3, $4)}
> }' toys
`%s` is for printing strings, `%d` is for printing integers.
将
printf()
与字段宽度规格一起使用。您不了解什么?显示您如何尝试在另一个问题上应用解决方案,我将重新打开以便更正。您的代码中printf()
在哪里?printf(“%-10s%-15s%-10s%d\n”,$1,$2,$3,$4)
我不明白链接问题的答案是这样的吗?您是从哪里想到使用\t
?非常感谢。我感谢你的帮助。