Often you may want to use Bash to find the common lines between two files.
You can use the grep command with the following syntax to do so:
grep -F -x -f teams1.txt teams2.txt
This particular example will return the common lines in the files named teams1.txt and teams2.txt.
Here is what the various grep operators do:
- -F: Specifies that lines should be interpreted as strings and not regular expressions.
- -x: Selects only matches that match the entire line.
- -f: Specifies that patterns will be obtained from files, one pattern per line.
The following example shows how to use this syntax in practice.
Example: How to Find Common Lines in Two Files in Bash
Suppose that have two files named teams1.txt and teams2.txt that both contain the names of various basketball teams.
We can use the cat command to view the contents of each file:

Suppose that we would like to find the lines that are in common between these two files.
We can use the following syntax to do so:
grep -F -x -f teams1.txt teams2.txt
The following screenshot shows how to use this syntax in practice:

This returns the following two teams that are in common between these two files:
- Phoenix Suns
- Dallas Mavericks
If we view the output from the cat command, we can confirm that these two team names do indeed appear in both files.
Note that the benefit of using the grep command is that the files do not need to be sorted in order for the common lines to be found.
This is in contrast to the comm command, which does require the files to be sorted.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Check if File Contains Specific String
Bash: How to Count Number of Unique Lines in File
Bash: How to Check if File is Empty
