grep - useful options

发布时间 2023-08-04 14:53:13作者: ZhangZhihuiAAA

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