多个文件每个文件的同样的第一列的情况下, 第三列相加,没有的就补零
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/tmp
$
cat
a
aa bb 1
dd
bb 2
aa bb 3
ee xx 4
/tmp
$
cat
b
bb cc 1
aa bbb 2
cc
dd
3
dd
ee 4
/tmp
$
cat
c
kk mm 3
dd
ee 2
aa
dd
1
bb ee 5
|
这个一般awk折腾的多点。 python代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/usr/bin/env python
import
sys
import
fileinput
fDict
=
{}
for
i
in
fileinput.
input
(sys.argv[
1
:]):
tmp
=
i.split()
fDict.setdefault(tmp[
0
], [
0
]
*
len
(sys.argv[
1
:]))
fDict[tmp[
0
]][sys.argv[
1
:].index(fileinput.filename())]
+
=
int
(tmp[
2
])
for
i
in
fDict:
print
i,
" "
.join([
str
(j)
for
j
in
fDict[i] ])
|
结果:
1
2
3
4
5
6
7
|
/tmp
$ .
/f
.py a b c
aa 4 2 1
bb 0 1 5
ee 4 0 0
dd
2 4 2
kk 0 0 3
cc 0 3 0
|
之前以为 fileinput.fileno 就是正在处理文件的index,结果是:
1
2
3
|
fileinput.fileno()
Return the integer “
file
descriptor”
for
the current
file
. When no
file
is
opened (before the first line
and
between files), returns
-
1.
|
好吧,这下记住了。
本文转自 nonono11 51CTO博客,原文链接:http://blog.51cto.com/abian/1790436,如需转载请自行联系原作者