如何从名为cars
的文件中找到此列的总和?
73
60
45
102
15
50
115
30
10
180
85
25
如何将这些数字加起来(使用命令行)? 我显示了此列表的输入内容
awk '{ print $4 }' cars
答案 0 :(得分:1)
给出:
$ cat file
73
60
45
102
15
50
115
30
10
180
85
25
您可以这样做:
$ paste -sd+ file | bc
790
或者,给定一个多列文件:
$ cat file
0 73 1
2 60 3
4 45 5
6 102 7
8 15 8
9 50 10
11 115 12
13 30 14
15 10 16
17 180 18
19 85 20
21 25 22
您可以使用cut
来获取感兴趣的列:
$ cut -f 2 file | paste -sd+ - | bc
790
答案 1 :(得分:0)
awk中的第一个解决方案: :能否请您尝试一次?只需更改变量的值,然后它将使用该列的SUM)
awk -v column_number=4 '{sum+=$column_number} END{print "SUM of column " column_number " is: " sum}' Input_file
通过运行以上代码,您可以在变量column_number
中提供任何列号,也可以使用其中的一些。如果您有其他要求,请在帖子的代码标签中向我们显示示例输入和预期的示例输出。
上述代码的解释:
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.
bash中的第二个解决方案: 考虑到您在Input_file中的行只有1个条目。
while read line; do sum=$(($sum+$line)) ; done < "Input_file"; echo "$sum"
答案 2 :(得分:0)
这是在命令行上执行此操作的方法,但不是awk。
from collections import defaultdict
d = defaultdict(list)
for k,v in zip(list3, list4):
d[k].append(v)
defaultdict(list, {1: ['a'], 2: ['b'], 3: ['c', 'd'], 4: ['e', 'f']})