searching string from one file and check it in the other file

Hello, Could you please help me in the script

I have two files:

FileOne
has the below data:

000004
500000
111234
123456

##################
FileTwo
has the below data:

434556          New York
545333          Paris
434344          Paris
111234          Berlin
434322          Boston
123456          Warsaw
443434          London
000334          Tokyo

##################

I have to check data from FileOne and check line after line if exist in FileTwo, if it exists print data from FileTwo

in this case, I should have:

111234                   Berlin
123456                   Warsaw

My idea is to do as below:

for qwerty in `awk ' { print $1 }' FileOne`     
do
  cat FileTwo | grep $qwerty > FinalFile
  cat FinalFile
done

But it doesn't work...
Whats your idea?

egrep -f file_one file_two
1 Like

Good solution, but egrep is a bit overkill. Even basic regular expressions aren't required. It's probably safest and swiftest to use fixed string matching. I'd suggest:

grep -Ff file_one file_two

Regards,
Alister

1 Like

In case the first field doesn't have a fixed length and may encouter subpattern matching

To enhance the matching (if your implementation support the standard output "-" notation) :

sed 's/.*/^& /' file_one | egrep -f - file_two
sed 's/.*/^& /' file_one | grep -Ff - file_two
1 Like

That last suggestion won't work. grep will try to match a literal ^ so long as -F is used.

However, you bring up a good point regarding substrings being matched and it's something to keep in mind in case the real data deviates from the sample data provided. Both grep suggestions assume not only that the first column is fixed-width, but also that its values will never appear in any way in the second column.

Regards,
Alister