我有一个包含以下数据的输入文件:
November 400
January 200
June 400
March 200
April 200
May 300
July 400
August 300
September 400
February 300
October 300
December 200
我必须创建一个循环结构来逐行处理数据文件,然后将其发送到输出文件,从而产生此输出
Month Sales
----- -----
January 200
February 300
March 200
April 200
May 300
June 400
July 400
August 300
September 400
October 300
November 400
December 200
Total show the total
Average show the average
我在获取数据并正确输出数据时遇到问题。我尝试使用 shell 检查来清理语法,但遇到了问题。这是代码。
#!bin/bash
awk >>practicefile.output
BEGIN{
print "Month\tSales"
print "-----\t-----"
{ Month[$1] = $2; next }
{ lines[(Month[$1])] = $1 (Month[$1]) $2 }
END {
for (i=1; i<=7; i++) {
if (lines[sales[i]])
print lines[month[i]]
else
print month, sales[i]
fi
}
}
答案1
我得到了想要的输出
Month Sales
----- -----
January 200
February 300
March 200
April 200
May 300
June 400
July 400
August 300
September 400
October 300
November 400
December 200
Total 3600
Average 300
使用以下脚本(另存为test.awk
):
BEGIN {
print "Month Sales"
print "----- -----"
}
{ printf "%-9s %s\n", $1, $2 }
{ sum += $2 }
END {
printf "\nTotal %s\n", sum
printf "\nAverage %s\n", sum / NR
}
并称其为sort -k1,1M input.txt | awk -f test.awk
.
说明:printf "%-9s", $1
向字符串 ( $1
) 添加最多 9 个字符的填充(带空格)。sort -k1,1M
按月对输入进行排序。不完全是 awk,但要简单得多。