Detailed usage of grep command in Linux

  
 

1. Function

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

2.Format

grep [options]

3. Main parameters

[options] Main parameters:

-c: Only the count of matching rows is output.

-I: Not case sensitive (only for single characters).

-h: The file name is not displayed when querying multiple files.

-l: When querying multiple files, only the file name containing the matching characters is output.

-n: Display matching lines and line numbers.

-s: Do not display error messages that do not exist or have no matching text.

-v: Shows all lines that do not contain matching text.

pattern regular expression main parameters:

\\: ignore the original meaning of special characters in regular expressions.

^: Match the start line of the regular expression.

$: Matches the end line of the regular expression.

\\<: Starts with a line that matches the regular expression.

\\>: End of the line that matches the regular expression.

[ ]: A single character, such as [A] that A meets the requirements.

[ - ]: Range, such as [A-Z], that is, A, B, C all the way to Z meet the requirements.

. : All single characters.

* : There are characters, the length can be 0.

4.grep Command Using Simple Instances

$ grep ‘test’ d*

Show all lines containing test in files starting with d.

$grep ‘test’ aa bb cc

Show lines matching test in aa, bb, cc files.

$grep ‘[a-z]\\{5\\}’ aa

Show all lines containing a string of at least 5 consecutive lowercase characters per string.

$grep ‘w\\(es\\)t.*\\1′ aa

If west is matched, es is stored in memory and marked as 1, then search Any number of characters (.*), followed by another es(\\1), will be displayed when found. If you use egrep or grep -E, you don't need to use the "\\” number to escape, directly write ’w(es)t.*\\1′

5.grep Command Using Complex Instances

Assuming you are searching for a file with string & rsquo;magic& rsquo; in the ’/usr/src/linux/Doc’ directory:

$ grep magic /usr/src/linux/Doc/*sysrq.txt:* How do I enable the magic SysRQ key?sysrq.txt:* How do I use the magic SysRQ key?

The file & rsquo;sysrp.txt’ contains the string and discusses the functionality of SysRQ.

By default, ’grep’ only searches the current directory. If there are many subdirectories under this directory, ’grep’ will be listed as follows: grep: sound: Is a directory

This may make the output of ’grep’ difficult to read. There are two solutions here: explicitly ask for a search subdirectory: grep -r or ignore subdirectories: grep -d skip

If there is a lot of output, you can pipe it to ’less’ Read on: $ grep magic /usr/src/linux/Documentation/*

Copyright © Windows knowledge All Rights Reserved