Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Monday, February 28, 2011

# Notes of grep search for files

Example of using grep

searching for the word "modules":

  grep -r "modules" .

By using the "-r" switch, we're telling grep to scan files in the current directory and all sub-directories. It will return a list of files the string was found in, and a copy of the line it was found on.

To just return the file name with out the line that matched: 

  grep -lr "modules" .

Use the grep to find strings match a regular expressions

  grep -lr "mod.*" .

That command will print a list of files containing any word starting with "mod".

to search for multiple words:

  grep -r "drupal\|joomla\|wordpress" .

Also to search for multiple patterns

# Interview question on grep:

A often asked question is to use grep to find the phone numbers in a very large file:

a folder consists of 10000 files and some files contain US phone numbers. What would you do to display the names of files containing US phone numbers?

For the following 4 kinds of patterns:
1. xxx-xxx-xxxx
2. (xxx)xxx-xxxx
3. xxx xxx xxxx
4. xxxxxxxxxx

grep '\(([0-9]\{3\})\|[0-9]\{3\}\)[ -]\?[0-9]\{3\}[ -]\?[0-9]\{4\}' file

Explanation:
([0-9]\{3\}) three digits inside parentheses
\| or
[0-9]\{3\} three digits not inside parens
...with grouping parentheses - \(...\) - around the alternation so the rest of the regex behaves the same no matter which alternative matches.
 
Some others

http://www.panix.com/~elflord/unix/grep.html

Suppose you want to match a specific number of repetitions of a pattern. A good example is phone numbers. 

You could search for a 7 digit phone number like this: grep "[[:digit:]]\{3\}[ -]\?[[:digit:]]\{4\}" fil


grep options search_string file...

http://www.macworld.com/article/41504/2004/12/jangeekfactor.html


If to
find the "same" line from two files, use
The correct solution is to avoid regular expressions and instead use fixed strings (-F) that must match an entire line (-x).
grep -Fxf file1 file2



--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

No comments:

Post a Comment