How to Use grep and Only Print Matching Pattern


You can use the grep command in Bash to return all lines from one or more files that match a particular pattern.

By default, grep will return the filename along with the entire line that contains the matching pattern.

To only print the matching pattern, you can use the following syntax:

grep -oh 'Mavs' *

This particular example will return only the matching pattern ‘Mavs’ from each line in each file in the current directory that contains ‘Mavs’ anywhere in the line.

Here is what the various commands do:

  • o: Prints only the matching pattern
  • h: Prevents the filename from being printed
  • *: Specifies that we would like to search all files in the current directory. You could also specify a specific filename to search instead.

The following example shows how to use this syntax in practice.

Example: How to Use grep and Only Print Matching Pattern

Suppose that our current directory has the following three files:

  • team_info1.txt
  • team_info2.txt
  • team_info3.txt

We can use the cat command to view the contents of each file:

Each file contains information about various basketball players including the team they play for and their total points scored.

Suppose that we would like to find all lines in each file that contain the pattern ‘Mavs’ and return only this matched pattern.

We can use the following syntax to do so:

grep -oh 'Mavs' *

The following screenshot shows how to use this syntax in practice:

grep print match only

Notice that this returns all lines from the file that match the pattern ‘Mavs’ and only this pattern is returned.

Suppose instead that we used the following syntax:

grep 'Mavs' *

The following screenshot shows how to use this syntax in practice:

Since we didn’t use the -o or -h flags, the grep command returns both the filename and the entire lines that match the pattern ‘Mavs.’

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Use grep to Get Line Number of Match
How to Use grep to Extract Last Occurrence in File
How to Use grep with Case-Insensitive Matching
How to Use grep to List All Files Containing Specific String

Leave a Reply