Using awk how do I combine data in two files and substitute values from the second file to the first file?

我怕爱的太早我们不能终老 提交于 2019-12-19 12:22:44

问题


Any ideas how to the following using awk?

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

data.txt contains some data:

A;1
B;2
A;3

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

The output should be as follows:

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

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.


回答1:


awk to the rescue!

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. note the order of files...




回答2:


awk solution:

awk -F';' 'NR==FNR{a[$1]=$2; next}{if($1 in a) $0=$0 FS a[$1]; print}' file2 file1

The output:

A1;1;2
A2;2;1
A3;3;0.5
A1;1;2
A2;2;1
A3;3;0.5

  • NR==FNR - processing the first file i.e. file2

  • a[$1]=$2 - accumulating additional values for each key

  • if($1 in a) $0=$0 FS a[$1] - appending value if first column matches



来源:https://stackoverflow.com/questions/44111737/using-awk-how-do-i-combine-data-in-two-files-and-substitute-values-from-the-seco

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!