Bash: How to Use find -exec with grep


Often you may want to use the find command in Bash to find specific files that match a pattern and then use grep to extract only the lines from those files that contain a specific string.

You can use the following syntax to do so:

find . -name '*.txt' -exec grep 'Forward' {} \; > out_data.txt

This particular example will do the following:

  • Find all files that contain the extension .txt
  • Extract only the lines from those files that contain the string ‘Forward’
  • Output these lines to a file name out_data.txt

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

Example: How to Use find -exec with grep in Bash

Suppose that our current directory is located at the following path:

  • c:/users/bobbi/data3

We can use the ls command to view all files in this directory:

We can see that this directory contains the following files:

  • eastern.txt
  • new_data.csv
  • old_data.csv
  • western.txt

Suppose that we would like to find all files in this current directory that contain the extension .txt and then find all lines in those files that contain the string ‘Forward’ somewhere in the line.

We can use the following syntax to do so:

find . -name '*.txt' -exec grep 'Forward' {} \; > out_data.txt

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

Bash find -exec grep

When we use the cat command to view the contents of the out_data.txt file we can see that it contains seven total lines that all contain the string ‘Forward’ somewhere in the line.

If you would also like to include the file name that each line in the output came from then you can use the -H operator after the grep command as follows:

find . -name '*.txt' -exec grep -H 'Forward' {} \; > out_data.txt

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

Bash find -exec grep with file name

When we use the cat command to view the contents of the out_data.txt file we can see that it contains each of the lines from the .txt files that contain ‘Forward’ and we can see which specific file each line came from.

Related Tutorials

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

Bash: How to Filter for Lines in File that Start with Specific String
Bash: How to Filter CSV File Based on Column Value
Bash: How to Filter for Rows where Column is Not Empty
Bash: How to Extract Specific Columns from CSV File

Leave a Reply