Follow Bird to learn the grep command of linux study notes

grep command

1. Function

The grep command in Linux is a powerful text search tool that uses regular expressions to search for text and print out the matching lines. The full name of grep is Global Regular Expression Print, which means the global regular expression version, and its use rights are all users.

2. Format

grep [options]

3. Main parameters (if you forget, you can refer to man grep)

[options] Main parameters:
-c: Only output the count of matching lines.
-I: case-insensitive (only applies to single characters).
-h: Do not display file names when querying multiple files.
-l: When querying multiple files, only output file names that contain matching characters.
-n: Display matching lines and line numbers.
-s: Do not display error messages for nonexistent or no matching text.
-v: Display all lines that do not contain matching text.

 4. Examples

  • 4.1 Find out which lines of the root and imix strings in the passwd file (passwd is a system file that stores user-related information grep –n “root\|imix” /etc/passwd

  • 4.2 Following 4.1, query the information of the first 4 lines and the last 3 lines that meet the conditions
    grep –n –B 4 –A 3 “imix” /etc/passed
  • 4.3 After entering df , cancel the lines related to tmpfs (df is used to check the disk space usage of the file system of the linux server )   
    df |grep -v tmpfs

5. Regular

 

character Meaning and Examples
^word

Meaning: The query string (word) is at the beginning of the line

Example: Query which line starts with # and list the line number

grep -n '^#' express.txt

word$

Meaning: The query string (word) is at the end of the line

Example: List which line ends with ! and display the line number

grep -n '!$' express.txt

.

Meaning: matches any single character

Example: Query string starts with eve, eae, eee, ee but not (ee)

grep -n 'e.e' express.txt

\

Meaning: Escape characters, remove the special meaning of special symbols

Example: Querying which row is left with single quotes '

grep -n \' express.txt

 *

Meaning: match the previous character ≥ 0 times

Example: Query the row where the strings of (es) (ess) (esss) , etc. are located

grep -n 'ess *'

 [list]

 Meaning: The specified characters are listed in query[]

Example: query aay,afy,aly

grep -n 'a[afl]y' express.txt

 [n1-n2]

 Meaning: Query out the specified character

 Example: Querying for lines starting with an uppercase letter

grep -n '^[A-Z]' express.txt

 [^list]

 意义:查询出不是list集合行(注: 那個^[]内时,代表的意义是反向选择)

示例:查询出字符串oog,ood但不能是oot

grep -n 'oo[^t]' express.txt

  \{n,m\}

 意义:

\{n,m\}查询出某个字符连续出现n到m次

\{n,\}查询出某个字符连续出现n次以上   

\{n\}查询出某个字符连续出现n次

示例:查询出在g与g之间有2个到3个o存在的行

grep -n 'go\{2,3\}g' express.txt

 

  

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326946074&siteId=291194637