List file names based on a filename pattern and file content?

zod picture zod · May 6, 2011 · Viewed 147.3k times · Source

How can I use Grep command to search file name based on a wild card "LMN2011*" listing all files with this as beginning?

I want to add another check on those file content.

If file content has some thing like

LMN20113456

Can I use GREP for this?

Grep -ls "LMN2011*"   "LMN20113456"

What is the proper way to search the file names and its contents using shell commands?

Answer

jm666 picture jm666 · May 6, 2011

Grep DOES NOT use "wildcards" for search – that's shell globbing, like *.jpg. Grep uses "regular expressions" for pattern matching. While in the shell '*' means "anything", in grep it means "match the previous item zero or more times".

More information and examples here: http://www.regular-expressions.info/reference.html

To answer of your question - you can find files matching some pattern with grep:

find /somedir -type f -print | grep 'LMN2011' # that will show files whose names contain LMN2011

Then you can search their content (case insensitive):

find /somedir -type f -print | grep -i 'LMN2011' | xargs grep -i 'LMN20113456'

If the paths can contain spaces, you should use the "zero end" feature:

find /somedir -type f -print0 | grep -iz 'LMN2011' | xargs -0 grep -i 'LMN20113456'