awk -v column_number=4 ' ##Starting awk program here and setting variable column_number value to 4 you could change it as per your column number too, for which you want to take SUM for all lines of Input_file.
{ ##Starting a BLOCK here.
sum+=$column_number ##Creating a variable named SUM whose value is value of current lines $column_number value and it keep adding SUMs value to its own to get cumulative sum of all columns in all lines.
} ##Closing BLOCK here.
END{ ##Mentioning awk program END block here, it will be executed when an Input_file is being done with reading.
print "SUM of column " column_number " of all lines in Input_file is: " sum ##Printing SUM variable value here.
}' Input_file ##Mentioning Input_file name here.
2nd Solution in bash: 考虑到Input_file中的行只有1个条目 .
while read line; do sum=$(($sum+$line)) ; done < "Input_file"; echo "$sum"
3 回答
鉴于:
你可以做:
或者,给定一个多列文件:
您可以使用
cut
获取感兴趣的列:这是在命令行上执行此操作的方法,但不是awk .
1st Solution in awk: 请问您可以尝试一次 . (由于您的尝试显示,我正在第4列的总和,编写了一个动态命令,您只需更改变量's value and it will take that column' s SUM)
通过运行上面的代码,您可以在变量
column_number
中提供任何列号,并且可以使用其中的一些 . 如果您有任何其他要求,请在帖子中向我们展示代码标签中的样本输入和预期样本输出 .Explanation of above code:
2nd Solution in bash: 考虑到Input_file中的行只有1个条目 .