Linux - join 2 CSV files

后端 未结 4 972
野趣味
野趣味 2020-12-17 18:36

I have 2 CSV files:

file_1 columns: id,user_id,message_id,rate
file_2 columns: id,type,timestamp

The relation between the files is that

4条回答
  •  被撕碎了的回忆
    2020-12-17 18:49

    You can try this:
    1. Change all lines to start with the key:

    awk -F',' { print $3 " file1 " $1 " " $2 " " $4 } < file1 >  temp
    awk -F',' { print $1 " file2 " $2 " " $3 }        < file2 >> temp
    

    Now the lines look like:

    message_id file1 id user_id rate
    id file2 type timestamp
    
    1. Sort temp by the first two columns. Now related lines are adjacent, with file1 first

      sort -k 1,1 -k 2,2 < temp > temp2

    2. Run awk to read the lines. In file1 lines save the fields, in file2 lines print them.

提交回复
热议问题