合并两个文件,​​一个关键的 - >值结构 [英] Merging two files with a key -> values structure

查看:106
本文介绍了合并两个文件,​​一个关键的 - >值结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找的想法,在外壳(Linux)的下一个问题,不是一个完整的解决方案。什么是最好的解决方案? (AWK,while循环,sed的....)

I am looking for ideas, not a complete solution for the next problem in shell(linux). What is the best solution? (awk, while-loop, sed ....)

我有两个文件具有相同的线结构:键 - 值值。我想合并这两个文件。如果该值不存在,则脚本插入一个新行。如果存在这样的脚本更新值(通过增加它们)。

I have two files with the same line structure: key-value-value. I want to merge these two files. If the value does not exist, the script insert a new line. If it exists the script updates the values (by adding them up).

Example:
File 1:

john-15-40
doo-10-91
mary-14-19
foo-11-0

File 2:

foo-110-10
john-22-11
ghost-1000-1000

Result:
foo-121-10
john-37-51
ghost-1000-1000
doo-10-91
mary-14-19

我怎样才能做到这一点?

How can I do this?

推荐答案

简单使用awk

awk '
  BEGIN {FS = OFS = "-"}
  {v1[$1] += $2; v2[$1] += $3}
  END {for (key in v1) {print key, v1[key], v2[key]}}
' F1 F2

这篇关于合并两个文件,​​一个关键的 - >值结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆