使用awk合并文件--生成report

来源:互联网 发布:deepin linux 15.4.1 编辑:程序博客网 时间:2024/05/20 05:55

假设有两个文件是这样的:

root@ubuntu:/home/zoer# cat id_name
1 naughty
2 cc
4 yy
3 zoer

root@ubuntu:/home/zoer# cat id_score
1 11
2 22
3 33
4 44

现在要求使用shell命令,做一份报告,报告格式:学生姓名+学生成绩。中间以空格分隔。

------------------------------------------------------------------------

root@ubuntu:/home/zoer# sort id_name >a
root@ubuntu:/home/zoer# sort id_score >b
root@ubuntu:/home/zoer# cat a
1 naughty
2 cc
3 zoer
4 yy
root@ubuntu:/home/zoer# cat b
1 11
2 22
3 33
4 44
root@ubuntu:/home/zoer# join a b>c
root@ubuntu:/home/zoer# cat c
1 naughty 11
2 cc 22
3 zoer 33
4 yy 44
root@ubuntu:/home/zoer# awk '{print $2," ",$3}' c
naughty   11
cc   22
zoer   33
yy   44

------------------------------------------------------------------------

上面列出了实现过程。首先对两个文件按照学号排序。排好序之后使用join命令将两个文件连接起来,然后使用awk输出后两列即可。

---------------------------------------------------------------------

上面是使用了join命令来帮忙。如果不使用join呢?看下面

root@ubuntu:/home/zoer# cat id_name id_score |sort -k 1 |awk 'BEGIN{t=""}{t=$1;if(tt==t){printf(" %s",$2);printf("\n")}else{printf("%s %s",$1,$2);}tt=t}'|awk '{print $2," ",$3}'
11   naughty
22   cc
33   zoer
44   yy

先排序,排序之后,相同id的学生信息都放在一起了。然后使用了两个awk来合并结果。【如果这里第一个awk的使用方法不明白,文章末尾还有一个例子来说明这个用法】

--》》》》》

上面的代码修改一下print,就可以只用一个awk命令了 。

root@ubuntu:/home/zoer# cat id_name id_score |sort -k 1 |awk 'BEGIN{t=""}{t=$1;if(tt==t){printf(" %s",$2);printf("\n")}else{printf("%s",$2);}tt=t}'
11 naughty
22 cc
33 zoer
44 yy

--------------------------------------------------------

再看一个awk的例子。去掉d文件中多余的第一个字段。

root@ubuntu:/home/zoer# cat d
m naughty
m cc
n zoer
n yy
n zz
root@ubuntu:/home/zoer# awk 'BEGIN{t=""}{t=$1;if(tt!=t)print $1,"\t",$2;else{print "\t",$2;}tt=t;}' d
m   naughty
      cc
n   zoer
     yy
     zz

上面的代码去掉了d文件中不必要的第一个字段。使用了记录第一个字段并且每次处理一行的时候比较第一个字段的技巧。

原创粉丝点击