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

后端 未结 2 1327
故里飘歌
故里飘歌 2021-01-17 08:56

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

2条回答
  •  长情又很酷
    2021-01-17 09:33

    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

提交回复
热议问题