50

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?

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
zod
  • 12,092
  • 24
  • 70
  • 106

5 Answers5

74

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'
clt60
  • 62,119
  • 17
  • 107
  • 194
35

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" ./
Jahanzeb Farooq
  • 1,948
  • 4
  • 27
  • 27
  • it would be nice to know, "how it can be done without find", really, only to share point of view – Victor Apr 08 '16 at 04:25
8
grep LMN20113456 LMN2011*

or if you want to search recursively through subdirectories:

find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;
Aoife
  • 1,736
  • 14
  • 12
  • How can i write the result filenames to a text file in the server – zod May 06 '11 at 17:30
  • 1
    Use grep -l to list matched filenames instead of matched lines and then redirect the output to a file. – Aoife May 06 '11 at 22:46
0

find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log

fedorqui
  • 275,237
  • 103
  • 548
  • 598
0

Assume LMN2011* files are inside /home/me but skipping anything in /home/me/temp or below:

find /home/me -name 'LMN2011*' -not -path "/home/me/temp/*" -print | xargs grep 'LMN20113456'
ohho
  • 50,879
  • 75
  • 256
  • 383