I would like to compare two files and get the output of matching string in one of the files at the end of the line:
Let’s say I have two files:-
file1:
xyzabcdef xyz abcdefghi
file2:
fghjkl wertyu abcdef
I could do something like this:
grep -Fif file2 file1
This gives me the following output:
xyzabcdef abcdefghi
This is because abcdef in file2 matches both of those lines in file1. However, what I would like is to just compare the end of the line in file1 to those in file2. So, I would like output to be:
xyzabcdef
Is there some magic command that will let me do this?
Advertisement
Answer
Extending Lars’s solution which I think the best option. Simply use the following:
cat -E file2 | grep -if - file1
The trick is to use -E
option of cat
to append $
at the end of each line. Then read the pattern from stdin using -
option of grep. Also you have to use regex matching, so I removed the -F
.