Join two files on Linux

前端 未结 5 1231
予麋鹿
予麋鹿 2021-01-15 21:51

I have two files; I want to join them.

$cat t1
 1 1.2
 2 2.2
$cat t2
 1
 2
 1

I want to have the output below

$cat joind.tx         


        
5条回答
  •  孤城傲影
    2021-01-15 22:32

    A simple awk is suffice for this:

    awk 'FNR==NR{a[$1]=$2;next} {print $1, a[$1]}' t1 t2
    1 1.2
    2 2.2
    1 1.2
    

    Breakup:

    NR == FNR {                  # While processing the first file
      a[$1] = $2                 # store the second field by the first
      next                       # move to next record in 1st file
    }
    {                            # while processing the second file
      print $1, a[$1]            # print $1 and the remembered
                                 # value from the first file.
    }
    

提交回复
热议问题