Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用shell绘制信息表_Shell_Awk - Fatal编程技术网

使用shell绘制信息表

使用shell绘制信息表,shell,awk,Shell,Awk,我在一个txt文件中得到了以下数据 Apple:Fruit:20:30 Leek:Vegetable:40:50 形式如下:(项目描述):(项目类别):(数量):(价格)。如何使用shell脚本绘制表格。有输出 Item Description Category Qty Price Total Sales ---------------------------------------------------------------

我在一个txt文件中得到了以下数据

Apple:Fruit:20:30
Leek:Vegetable:40:50
形式如下:(项目描述):(项目类别):(数量):(价格)。如何使用shell脚本绘制表格。有输出

Item Description           Category          Qty       Price        Total Sales
--------------------------------------------------------------------------------
Apple                      Fruit             20         $30.00         $600.00
Leek                       Vegetable         40         $50.00         $2000.00

其中总销售额等于数量x价格。请帮忙。提前谢谢

这可以让你开始

awk '{printf "%-27s%-18s%-11s$%-14.2f$%.2f\n",$1,$2,$3,$4,$3*$4}' FS=: foo.txt
结果

Apple Fruit 20 $30.00 $600.00 Leek Vegetable 40 $50.00 $2000.00 苹果水果20$30.00$600.00 韭菜40$50.00$2000.00
您可以使用awk进行计算,但使用column来计算列大小更简洁(更可靠):

awk 'BEGIN { FS=":" ; print "Item description:Category:Qty:Price:Total sales"}
    {printf("%s:%s:%i:$%.2f:$%.2f\n",$1,$2,$3,$4,$3*$4)}' INPUTFILE | column -t -s:

我将分隔行的打印留给您(例如,使用awk捕获
s输出,在第一行之后计算
$0
,等等)

我将在awk中执行计算和货币格式设置,使用列作为表间距,然后使用sed添加行:

awk -F: -v OFS=: '
    BEGIN {print "Item Description","Category","Qty","Price","Total Sales" }
    { $(NF+1) = $3*$4; $4 = sprintf("$%.2f", $4); $5 = sprintf("$%.2f", $5); print }
' file.txt |
column -s: -t | 
sed '1{p;s/./-/g}'

在哪里指定文件?在FS下?如何打印分隔符?尝试放置\n然后再加上破折号,但没有让我走远。
Item Description  Category   Qty  Price   Total Sales
-----------------------------------------------------
Apple             Fruit      20   $30.00  $600.00
Leek              Vegetable  40   $50.00  $2000.00