shell多个文件按照用户每月消费合并成多列
有个报表统计需求,现在有各个月份的用户消费报表:
201209.txt
A 50
B 10
C 30
201208.txt
B 30
C 20
D 10
201207.txt
A 3
B 5
D 3
....
需要合并成每个用户每月的消费,没有消费的月份填0:
用户 201209 201208 201207
A 50 0 3
B 10 30 5
C 30 20 0
D 0 10 3
使用shell如何实现。
Mr.小皓
12 years, 4 months ago
Answers
[root@localhost ~]# more 20120*
::::::::::::::
201207.txt
::::::::::::::
A 3
B 5
D 3
::::::::::::::
201208.txt
::::::::::::::
B 30
C 20
D 10
::::::::::::::
201209.txt
::::::::::::::
A 50
B 10
C 30
[root@localhost ~]# cat aa.sh
#!/bin/bash
u=`cat *.txt | awk '{print $1}' | sort -u | tr "\n" " "`
m=`ls *.txt | awk -F. '{print $1}' | tr "\n" " "`
echo "user $m"
for i in $u ; do
echo -n "$i "
for j in $m ; do
p=`grep $i $j.txt | awk '{print $2}'`
echo -n "${p:=0} "
done
echo
done
[root@localhost ~]# bash aa.sh
user 201207 201208 201209
A 3 0 50
B 5 30 10
C 0 20 30
D 3 10 0
[root@localhost ~]#
思路是以用户为索引来获取每月的数据。
无界D孤星
answered 12 years, 4 months ago