Unix: merge 2 files using 2nd column

I would like to merge the two files according to the content of their 2nd column.

File 1:

"4742"  "209220_at"     2.60700394801826
"104"   "209396_s_at"   2.60651442103297
"749"   "202409_at"     2.59424724783704
"4168"  "209875_s_at"   2.58773204877464
"3973"  "1431_at"       2.52832098784342
"1826"  "207201_s_at"   2.41685345240968

File2:

"653"   "1431_at"       2.14595534191867
"1109"  "207201_s_at"   2.13777517447307
"353"   "212531_at"     2.12706340284672
"381"   "206535_at"     2.11456707231618
"1846"  "204534_at"     2.10919474441178

Finally:

"3973"  "1431_at"       2.52832098784342 "653"   "1431_at"       2.14595534191867
"1826"  "207201_s_at"   2.41685345240968 "1109"  "207201_s_at"   2.13777517447307

I tried comm, diffsome kind of obscure awksingle-line without any success. Any help is greatly appreciated. Ben

+5
source share
4 answers
awk '
  # store the first file, indexed by col2
  NR==FNR {f1[$2] = $0; next}
  # output only if file1 contains file2 col2
  ($2 in f1) {print f1[$2], $0}
' file1 file2
+2
source

You can do this with a combination of sortand join. Direct approach

join -j2 <(sort -k2 file1) <(sort -k2 file2)

but it looks a little different than what you are looking for. It just shows the common join field, and then the rest of the fields from each file

"1431_at" "3973" 2.52832098784342 "653" 2.14595534191867
"207201_s_at" "1826" 2.41685345240968 "1109" 2.13777517447307

, , join

join -o 1.1,1.2,1.3,2.1,2.2,2.3 -j2 <(sort -k2 file1) <(sort -k2 file2)

-o FILENUM.FIELDNUM.

, <(), , POSIX sh, , POSIX sh.

+5

, (Perl, Python Ruby - ), , , , , ( -) .

, , unix, ( ) .

0
awk 'FNR==NR{a[$2]=$0} NR>FNR && ($2 in a){ print $0,a[$2] } ' file2 file1
0

All Articles