Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 575
zod Avatar asked May 06 '11 16:05

zod


People also ask

How do I find a file with a specific pattern in Linux?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do I grep a filename in a directory?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.

How do I grep a pattern from a file?

To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.


1 Answers

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' 
like image 105
jm666 Avatar answered Oct 13 '22 19:10

jm666