Dave
Dave

Reputation: 525

Linux terminal: Recursive search for string only in files w given file extension; display file name and absolute path

I'm new to Linux terminal; using Ubuntu Peppermint 5.

I want to recursively search all directories for a given text string (eg 'mystring'), in all files which have a given file extension (eg. '*.doc') in the file name; and then display a list of the file names and absolute file paths of all matches. I don't need to see any lines of content.

This must be a common problem. I'm hoping to find a solution which does the search quickly and efficiently, and is also simple to remember and type into the terminal.

I've tried using 'cat', 'grep', 'find', and 'locate' with various options, and piped together in different combinations, but I haven't found a way to do the above.

Something similar was discussed on: How to show grep result with complete path or file name

and: Recursively search for files of a given name, and find instances of a particular phrase AND display the path to that file

but I can't figure a way to adapt these to do the above, and would be grateful for any suggestions.

Upvotes: 3

Views: 5912

Answers (2)

Klaus
Klaus

Reputation: 25623

find . -name '*.doc' -exec grep -l 'mystring' {} \; -print

How it works:

find searches recursively from the given path .

for all files which name is '*.doc'

-exec grep execute grep on files found

suppress output from grep -l

and search inside the files for 'mystring'

The expression for grep ends with the {} \;

and -print print out all names where grep founds mystring.

EDIT: To get only results from the current directory without recursion you can add: -maxdepth 0 to find.

Upvotes: 2

Thomas Dickey
Thomas Dickey

Reputation: 54524

According to the grep manual, you can do this using the --include option (combined with the -l option if you want only the name — I usually use -n to show line numbers):

--include=glob

Search only files whose name matches glob, using wildcard matching as described under --exclude.

-l

--files-with-matches

Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning of each file stops on the first match. (-l is specified by POSIX.)

A suitable glob would be "*.doc" (ensure that it is quoted, to allow the shell to pass it to grep).

GNU grep also has a recursive option -r (not in POSIX grep). Together with the globbing, you can search a directory-tree of ".doc" files like this:

grep -r -l --include="*.doc" "mystring" .

If you wanted to make this portable, then find is the place to start. But using grep's extension makes searches much faster, and is available on any Linux platform.

Upvotes: 6

Related Questions