使用awk如何将数据合并到两个文件中,并将值从第二个文件替换为第一个文件? [英] Using awk how do I combine data in two files and substitute values from the second file to the first file?

查看:104
本文介绍了使用awk如何将数据合并到两个文件中,并将值从第二个文件替换为第一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么想法如何使用awk进行以下操作?

Any ideas how to the following using awk?

两个输入文件,data.txt和keys.txt:

Two input files, data.txt and keys.txt:

data.txt包含一些数据:

data.txt contains some data:

A;1
B;2
A;3

keys.txt包含键;值"对(在此示例中,"C"不是data.txt的一部分,但awk脚本仍应工作):

keys.txt contains "key;value" pairs ("C" is in this example not part of data.txt, but the awk script should still work):

A;30
B;20
C;10

输出应如下:

A;1;30
B;2;20
A;3;30

因此,data.txt中的每行包含来自keys.txt的任何键,都应将相应的值附加到data.txt中的行.

Hence, each row in data.txt that contains any key from keys.txt should get the corresponding value appended to the row in data.txt.

推荐答案

awk进行救援!

假定第二个文件具有与第一个文件不同的唯一键(如果不需要,则需要指定随后发生的事情)

assumes the second file has unique keys unlike first file (if not you need to specify what happens then)

$ awk 'BEGIN   {FS=OFS=";"} 
       NR==FNR {a[$1]=$2; next} 
       $1 in a {print $0,a[$1]}' file2 file1

A;1;30
B;2;20
A;3;30

ps.注意文件的顺序...

ps. note the order of files...

这篇关于使用awk如何将数据合并到两个文件中,并将值从第二个文件替换为第一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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