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.

Removing lines that are in fileB from fileA producing fileC

Problem

You have two different files fileA and fileB containing similar records (one record per line), and you would like to remove the records that fileB contains from fileA (subtract) producing a new file (fileC) that contains only records that are contained in fileA with records from fileB removed.

Solution

Use the following grep command

grep -vxf fileB fileA > fileC

Search for content in files in linux (recursively and case-independent)

Problem

You would like to find the files that contain some specific text, and would like to do it recursively (ie in a project folder), using something simpler than the find command.

Solution

You can use the following in your current top folder to search recursively, case-independent and by displaying the file number that the searched text appears, with the following:

grep -rin "TextToBeSearched" .