How can I grep content from file 1 to match file2 and put them in file2

I have file1.txtwith content:

rs002
rs113
rs209
rs227
rs151 
rs104

I have file2.txtwith content:

rs113   113
rs002   002
rs227   227
rs209   209
rs104   104
rs151   151

I want to get strings file2.txtthat match the entries in file1.txtfor which I tried:

grep -Fwf file1.txt file2.txt 

with the output as follows:

rs113   113
rs002   002
rs227   227
rs209   209
rs104   104
rs151   151

This retrieves all matching rows, but is in order of appearance in file2.txt. Is there a way to retrieve matching records while maintaining order s file1.txt? The required output is as follows:

rs002   002
rs113   113
rs209   209
rs227   227
rs151   151
rs104   104
+4
source share
4 answers

One (unusually not very elegant) solution is to iterate over file1.txtand find a match for each row:

while IFS= read -r line; do
    grep -wF "$line" file2.txt
done < file1.txt

which gives way

rs002   002
rs113   113
rs209   209
rs227   227
rs151   151
rs104   104

, , , grep :

grep -m 1 -wF "$line" file2.txt

GNU, .

, -, , , , , , .

+2

grep. file2.txt , .. , , awk:

 awk 'FNR==NR { f2[$1] = $2; next } $1 in f2 { print $1, f2[$1] }' file2.txt file1.txt

:

rs002 002
rs113 113
rs209 209
rs227 227
rs151 151
rs104 104
+2

sed- 2

 sed 's#^\([^ ]*\)\(.*\)#/\1/ s/$/\2/#' file2 > tmp.sed
 sed -f tmp.sed file1

, tmp

sed -f <(sed 's#^\([^ ]*\)\(.*\)#/\1/ s/$/\2/#' file2) file1
0
source

This should help (but not optimal for large input):

$ for line in `cat file1.txt`; do grep $line file2.txt; done
-1
source

All Articles