Grep Include Only *.txt File Pattern When Running Recursive Mode

I‘m using Debian Linux as my development workstation. I would like to search a directory called ~/projects/ recursively for “foo” word only for *.txt files. How do I search all text files in ~/projects/ for “foo” word using grep command?

The grep command supports recursive file pattern option as follows:

grep -R "pattern" /path/to/dir/

To limit your search for *.txt, try passing the --include option to grep command

Syntax and examples for --include option

The syntax is:

grep -R --include=GLOB "pattern" /path/to/dir
grep -R --include="*.txt" "pattern" /path/to/dir
grep -R --include="*.txt" "foo" ~/projects/

You can include files whose base name matches GLOB using wildcard matching. A file-name glob can use *, ?, and […] as wildcards, and to quote a wildcard or backslash character literally. You can ignore case distinctions in both the PATTERN and the input files with -i optoon i.e. case-insensitive search. In this following example, search for all *.py, *.pl, and *.sh files for “main” word in my /raid6/projects/sysmanagement/ directory:

grep --color -Ri --include="*.py" --include="*.sh" --include="*.pl" "main" /raid6/projects/sysmanagement/


grep --color -Ri  --include=*.{py,pl,sh} "main" /raid6/projects/sysmanagement/

OR a safer option would be (note –color removed and * replaced with *):

grep -Ri  --include=*.{py,pl,sh} "main" /raid6/projects/sysmanagement/

The --include option provides you the following advantages:

  1. Speed up the search.
  2. Only match given file pattern.
  3. Do not search for binary files such as compiled files or image files. In other words only look for *.txt or *.py file patterns and so on.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts