ZhangZhihui's Blog  

The “ -c ” option counts the number of occurrences of a string: even though ABC4.sh has no matches, it still counts them and returns zero:
grep –c abc *sh
The output of the preceding command is here:
ABC4.sh:0
abc3.sh:3


The “ -e ” option lets you match patterns that would otherwise cause syntax problems (the “–” character normally is interpreted as an argument for grep ):
grep –e "-abc" *sh
abc3.sh:ends with -abc
The “ -e ” option also lets you match multiple patterns:
grep –e "-abc" -e "comment" *sh
ABC4.sh:# ABC in a comment
abc3.sh:ends with -abc

 

Use the “ -iv ” options to display the lines that do not contain a specified string using a case insensitive match:
grep –iv abc *sh
ABC4.sh:
abc3.sh:this line won't match


The “ -l ” option is to list only the filenames that contain a successful match (note this matches contents of files, not the filenames). The Word document matches because the actual text is still visible to grep , it is just surrounded by proprietary formatting gibberish. You can do similar things with other formats that contain text, such as XML, HTML, CSV, and so forth:
grep -l abc *

The “ -l ” option is to list only the filenames that contain a successful match:
grep –l abc *sh
Use the “ -il ” options to display the filenames that contain a specified string using a case insensitive match:
grep –il abc *doc
The preceding command is very useful when you want to check for the occurrence of a string in Word documents.

 

The “ -n ” option specifies line numbers of any matching file:
grep –n abc *sh
abc3.sh:1:abc at start
abc3.sh:2:ends with -abc
abc3.sh:3:the abc is in the middle


The “ -h ” option suppresses the display of the filename for a successful match:
grep –h abc *sh
abc at start
ends with -abc
the abc is in the middle

 

The " -o" option shows only the matched string (this is how you avoid returning the entire line that matches):
The " -o" option followed by the " -b" option shows the position of the matched string (returns character position, not line number. The "o" in “one” is the 59th character of the file):

$ grep -o -b one columns4.txt
59:one

 

You can specify a recursive search, as shown here:
grep –r abc /etc

 

If you want to exclude everything except for an exact match, you can use the –w option.

 

The --color switch displays the matching string in color:

 

You can use the pair of metacharacters ( .* ) to find the occurrences of two words that are separated by an arbitrary number of intermediate characters.

The following command finds all lines that contain the strings one and three with any number of intermediate characters:
grep "one.*three" columns4.txt
one two three

 

You can “invert” the preceding result by using the –v switch.

posted on 2023-08-04 14:46  ZhangZhihuiAAA  阅读(5)  评论(0编辑  收藏  举报