bash – Fetching lines from files

Question:

Gentlemen, is there a quick way to select lines that are duplicated in 2 files?

For example:

file1.txt

MariaFeudorIvanNikolay

file2.txt

DmitryElenaAntonMariaEvgenyIvan

At the exit you need to get

MariaIvan

Any compact and fast solution, maybe through diff?

Answer:

You can use the join command. She perfectly solves the task, although she can do more.

join file1.txt file2.txt

The command will issue a warning that you should first sort the files and lines found in both files

:~> join file1.txt file2.txt join: file 2 is not in sorted orderjoin: file 1 is not in sorted orderMariaIvan

Addition (as suggested by PocketSam ): Files can be sorted with the sort command. The next line sorts one of the files, merges and deletes the temporary file.

:~> FILE2=$( mktemp ) && sort file2.txt > $FILE2 && \sort file1.txt | join - $FILE2 && rm $FILE2

outputs:

IvanMaria
Scroll to Top