List file names based on a filename pattern and file content?
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?
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'
It can be done without find
as well by using grep's "--include"
option.
grep man page says:
--include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).
So to do a recursive search for a string in a file matching a specific pattern, it will look something like this:
grep -r --include=<pattern> <string> <directory>
For example, to recursively search for string "mytarget" in all Makefiles:
grep -r --include="Makefile" "mytarget" ./
Or to search in all files starting with "Make" in filename:
grep -r --include="Make*" "mytarget" ./