-1

I have a file containing following numbers file1.txt

1
5
6
8
14

I have another file named rmsd.txt which contains values like the following

1 2.12
2 3.1243
3 4.156
4 3.22
5 3.882
6 8.638
7 8.838
8 7.5373
9 10.7373
10 8.3527
11 3.822
12 5.672
13 7.23
14 5.9292

I want to get the values of column 2 from rmsd.txt for the numbers present in file.txt. I want to get something like the following

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292

I can do that by do like that grep 1 rmsd.txt and so on but it will take a long time. I was trying a for loop something like

for a in awk '{print $1}' file.txt; do
grep $a rmsd.txt >result.txt
done

But it didn't work. Maybe it is very simple and I am thinking in a wrong direction. Any help will be highly appreciated.

  • How is this asked every single day... Did you try searching `how to match field from one file in another` on google? – 123 Jun 07 '17 at 19:24

3 Answers3

0
for WORD in `cat FILE`
do
   echo $WORD
   command $WORD > $WORD
done

Origina source

EDIT: Here is your code with few fixes:

for a in `awk '{print $1}' file.txt`
do
    grep $a rmsd.txt >>result.txt
done
Marek Vitek
  • 1,573
  • 9
  • 20
0

This is tailor made job for awk:

awk 'NR==FNR{a[$1]; next} $1 in a' file1.txt msd.txt

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292

Most likely it a duplicate, as soon as I find a good dup, I will mark it so.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

awk to the rescue!

$ awk 'NR==FNR{a[$1];next} $1 in a' file1 file2

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292

or with sort/join

$ join <(sort file1) <(sort file2) | sort -n

or grep/sed

$ grep -f <(sed 's/.*/^&\\b/' file1) file2
karakfa
  • 66,216
  • 7
  • 41
  • 56