1. Search for the specified string from a single file:
$ grep "literal-string" filename
The command outputs the contents of the string in the file, and if the string has no spaces, it can be without double quotes. FileName can be multiple files, with each file separated by a space.
The plus -i
parameter can ignore the case. Add -u
parameter to search for a word instead of searching for a string with that word
2. Display multiple lines near the matching line:
- -a displays n rows after matching rows
$ grep-a N "string" filename
- -B Displays the n rows before matching rows
$ grep-b N "string" filename
- -c display n rows before and after matching rows
$ grep-c N "string" filename
3. Recursive Search:
-r
$ GREP-R "This" *
Search for all files with "This" in the current directory and sub-directories.
4, do not match the search:
-v
$ grep-v "Go" demo_text
Displays rows that do not contain the search string "go".
5. Number of rows matched by statistics:
-c
$ grep-c "Go" filename
The number of rows in the statistics file that contain a "go" string.
6. Only file names with strings are displayed:
-l
$ grep-l "this" filename
Displays the file name of the file with the "this" string.
7. Display line number when output:
Grep-n "this" filename
Displays the line number of the line that contains the "this" string in the file.
Introduction to common methods of GREP commands under Linux