Producing a file C.txt that contains common lines between A.txt B.txt using grep

Problem

You have two files (A.txt, B.txt) that contain records (one line each), and you want to find out the common lines between the two.

For example you have the following two files.

A.txt

one
two
three

and B.txt

two
six
seven

and you want to find or produce a new file (C.txt) that contains only the common record (two) from the two files.

Solution

You can use grep with the -Fx options like

grep -Fxf A.txt B.txt > C.txt

that will produce file C.txt that contains the common line (two) from the two files.

The options for grep have the following meaning:

  • -F: Interpret the pattern as a list of fixed strings (instead of regular expressions).
  • -x: Only match whole lines.
  • -f fileA.txt: Read the patterns from fileA.txt.