You can use join
here:
join -j 2 -o 1.1 2.1 <(sort -nk2,2 nid8.txt) <(sort -nk2,2 nid9.txt)
Use the second field -j 2
on both files as the keys.
and -o
utput these fields:
first field from the first file 1.1
first field from the second file 2.1
join
requires input files to be sorted, so we sort them on the second field that will be used as the key numerically sort -nk2,2 input
.
Using awk
which not require to have sorted inputs but load first input file into memory:
awk '!second_file{ my_array[$2]=$1; next }
($2 in my_array) { print $1, my_array[$2] }' nid8.txt second_file=1 nid9.txt
with my_array[$2]=$1
we are saving first column of first input file nid8.txt only where the keys are the second column of the same first file until second_file
variable value is not set to 1 which cause !second_file
expression value evaluate to false and won't execute that block for next input(s).
With ($2 in my_array)
condition we checks if the second field exist in our array my_array or not, if that was exist then we print first field $1
(which is from the second file) and the value for that same key with my_array[$2]
which contains the first field from the first file with the same key.