Introduction to Linux command grep

Sep 04, 2017 pm 02:12 PM
grep linux introduce

1. Function

The grep command in Linux system is a powerful text search tool. It can use 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. Its usage permissions are for all users.

2. Format

grep [options]

3. Main parameters

[options]Main parameters:

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

-I: Insensitive to uppercase and lowercase (only applicable to single characters).

-h: Do not display the file name when querying multiple files.

-l: When querying multiple files, only the file names containing matching characters will be output.

-n: Display matching lines and line numbers.

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

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

pattern Regular expression main parameters:

\: Ignore the original meaning of special characters in the regular expression.

^: matches the starting line of the regular expression.

$: Matches the end line of the regular expression.

\<: Start from the line matching the regular expression.

\>: To the end of the line matching the regular expression.

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

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

. : All single characters.

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

4. A simple example using the grep command

$ grep ‘test’ d*

Displays the lines containing test in all files starting with d.

$ grep ‘test’ aa bb cc

Display the lines matching test in the aa, bb, cc files.

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

Displays all lines containing strings each of which has at least 5 consecutive lowercase characters.

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

If west is matched, es is stored in memory and marked as 1, and then searches for any characters (.*), these characters are followed by another es (\1), and the line is displayed when found. If you use egrep or grep -E, there is no need to escape with the "\" sign, just write it directly as 'w(es)t.*\1'.

5.grep command usage complex example

Suppose you are searching for files with the string 'magic' 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 'sysrp.txt' contains this string and discusses the function of SysRQ.

By default, 'grep' only searches the current directory. If there are many subdirectories under this directory, 'grep' will list it like this:

grep: sound: Is a directory

This may make the output of 'grep' difficult to read. There are two solutions here:

Explicitly request to search subdirectories: grep -r

or ignore subdirectories: grep -d skip

If there is a lot of output, You can pipe it to 'less' to read:

$ grep magic /usr/src/Linux/Documentation/* | less

This way you can read it more conveniently .

One thing to note is that you must provide a file filtering method (use * to search all files). If you forget, 'grep' will wait until the program is interrupted. If you encounter this, press and try again.

There are some interesting command line parameters below:

grep -i pattern files: Search case-insensitively. The default is case-sensitive,

grep -l pattern files: Only matching file names are listed,

grep -L pattern files: Unmatched file names are listed,

grep -w pattern files: only match the entire word, not part of the string (such as matching 'magic', not 'magical'),

grep -C number pattern files: match the context respectively Display [number] lines,

grep pattern1 | pattern2 files: Display lines matching pattern1 or pattern2,

grep pattern1 files | grep pattern2: Display lines matching both pattern1 and pattern2.

grep -n pattern files can display the line number information

grep -c pattern files can find the total number of lines

There are also some special symbols for searching:

\< and \> mark the beginning and end of words respectively.

For example:

grep man * will match 'Batman', 'manic', 'man', etc.

grep '\

grep '\' only matches 'man', not other strings such as 'Batman' or 'manic'.

'^': means that the matched string is at the beginning of the line,

'$': means that the matched string is at the end of the line,

Grep command usage list

1. Parameters:

-I: Ignore case

-c: Print the number of matching lines

-l: Find files containing Matches

-v: Find lines that do not contain matches

-n: Print lines and line labels that contain matches

2, RE (regular expression)

\ Ignore the original meaning of special characters in the regular expression

^ Match the beginning line of the regular expression

$ Match the end line of the regular expression

\< Start with the line matching the regular expression

\> To the end of the line that matches the regular expression

[ ] Single character; such as [A] means A meets the requirements

[ - ] Range; such as [A-Z] means A , B, C to Z all meet the requirements

. All single characters

* All characters, the length can be 0

3. Example

# ps -ef | grep in.telnetd

root 19955 181 0 13:43:53 ? 0:00 in.telnetd

# more size.txt Contents of size file

b124230

b034325

a081016

m7187998

m7282064

a022021

a061048

m9324822

b103303

a013386

b044525

m8987131

B081016

M45678

B103303

BADc2345

# more size.txt | grep '[a-b]' range; such as [A-Z], that is, A, B, C to Z all meet the requirements

b124230

b034325

a081016

a022021

a061048

b103303

a013386

b044525

# more size.txt | grep '[a-b]'*

b124230

b034325

a081016

m7187998

m7282064

a022021

a061048

m9324822

b103303

a013386

b044525

m8987131

B081016

M45678

B103303

BADc2345

# more size.txt | grep 'b' single character; For example, [A] means A meets the requirements

b124230

b034325

b103303

b044525

# more size.txt | grep ' [bB]'

b124230

b034325

b103303

b044525

B081016

B103303

BADc2345

# grep 'root' /etc/group

root::0:root

bin::2:root,bin,daemon

sys::3:root,bin,sys,adm

adm::4:root,adm,daemon

uucp::5:root,uucp

mail::6:root

tty::7:root,tty,adm

lp::8:root,lp,adm

nuucp::9:root ,nuucp

daemon::12:root,daemon

# grep '^root' /etc/group matches the starting line of the regular expression

root::0: root

# grep 'uucp' /etc/group

uucp::5:root,uucp

nuucp::9:root,nuucp

# grep '\

uucp::5:root,uucp

# grep 'root$' /etc/group Match the end line of the regular expression

root::0:root

mail::6:root

# more size.txt | grep -i 'b1..*3' -i : Ignore size Write

b124230

b103303

B103303

# more size.txt | grep -iv 'b1..*3' -v: Find does not contain Matching row

b034325

a081016

m7187998

m7282064

a022021

a061048

m9324822

a013386

b044525

m8987131

B081016

M45678

BADc2345

# more size.txt | grep -in 'b1..*3'

1:b124230

9:b103303

15:B103303

# grep '$' /etc/init.d/nfs.server | wc -l

128

# grep '\$' /etc/init.d/nfs.server | wc -l Ignore the original meaning of special characters in regular expressions

15

# grep '\$' /etc/init.d/nfs.server

case " $1" in

>/tmp/sharetab.$$

[ "x$fstype" != xnfs ] &&

echo "$path\t$res\ t$fstype\t$opts\t$desc"

>>/tmp/sharetab.$$

/usr/bin/touch -r /etc/dfs/sharetab / tmp/sharetab.$$

/usr/bin/mv -f /tmp/sharetab.$$ /etc/dfs/sharetab

if [ -f /etc/dfs/dfstab ] && /usr/bin/egrep -v '^[ ]*(#|$)'

if [ $startnfsd -eq 0 -a -f /etc/rmmount.conf ] &&

if [ $startnfsd -ne 0 ]; then

elif [ ! -n "$_INIT_RUN_LEVEL" ]; then

while [ $wtime -gt 0 ]; do

wtime=`expr $wtime - 1`

if [ $wtime -eq 0 ]; then

echo "Usage: $0 { start | stop }"

# more size.txt

the test file

their are files

The end

# grep 'the' size.txt

the test file

their are files

# grep '\

the test file

their are files

# grep 'the\>' size.txt

the test file

# grep '\' size.txt

the test file

# grep '\<[Tt]he\>' size.txt

the test file

========== ================================================== ======

1,Introduction

A multi-purpose text search tool using regular expressions. This php?name=%C3%FC%C1%EE" onclick="tagshow(event)" class="t_tag"> command is originally an ed line editor A php?name=%C3%FC%C1%EE" onclick="tagshow(event)" class="t_tag">Command/Filter:

g/re/p -- global - regular expression - print.

Basic format

grep pattern [file...]

(1)grep search string [filename]

(2)grep regular expression [filename]

Search for all occurrences of pattern in the file. Pattern can be either a string to be searched or a regular expression.

Note: It is best to use double quotes when entering the string to be searched/and when using regular expressions for pattern matching, pay attention to using single quotes

2, grep option

-c Only output the count of matching lines

-i is case-insensitive (for single characters)

-n displays matching line numbers

-v does not display non-containing matches All lines of text

-s does not display error messages

-E uses extended regular expressions

For more options, please see: man grep

3, Commonly used grep examples

(1) Multiple file query

grep "sort" *.doc #See file name matching

(2) Line matching: Output the count of matching lines

grep -c "48" data.doc #Output the number of lines containing 48 characters in the document

(3) Display matching lines and number of lines

grep -n "48" data.doc #Display all lines and line numbers that match 48

(4) Display non-matching lines

grep -vn "48" data.doc # Output all lines that do not contain 48

(4) Display non-matching lines

grep -vn "48" data.doc #Output all lines that do not contain 48

(5) Case sensitive

grep -i "ab" data.doc #Output all lines containing strings of ab or Ab

4, application of regular expressions

(1)Application of regular expressions (note: it is best to enclose regular expressions in single quotes)

grep '[239].' data.doc #Output all files that contain numbers ending with 2, 3 or Lines starting with 9 and containing two numbers

(2) Mismatch test

grep '^[^48]' data.doc #Does not match lines whose beginning is 48

(3) Use extended pattern matching

grep -E '219|216' data.doc

(4) ...

This needs to be Continuously apply and summarize in practice, and master regular expressions proficiently.

5, use class name

You can use the class name for international pattern matching:

[[:upper:]] [A-Z]

[[ :lower:]] [a-z]

[[:digit:]] [0-9]

[[:alnum:]] [0-9a-zA-Z]

[[:space:]] Space or tab

[[:alpha:]] [a-zA-Z]

(1) Use

grep '5[[:upper:]][[:upper:]]' data.doc #Query lines starting with 5 and ending with two capital letters

The above is the detailed content of Introduction to Linux command grep. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

What is the main purpose of Linux? What is the main purpose of Linux? Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

How to run sublime after writing the code How to run sublime after writing the code Apr 16, 2025 am 08:51 AM

There are six ways to run code in Sublime: through hotkeys, menus, build systems, command lines, set default build systems, and custom build commands, and run individual files/projects by right-clicking on projects/files. The build system availability depends on the installation of Sublime Text.

laravel installation code laravel installation code Apr 18, 2025 pm 12:30 PM

To install Laravel, follow these steps in sequence: Install Composer (for macOS/Linux and Windows) Install Laravel Installer Create a new project Start Service Access Application (URL: http://127.0.0.1:8000) Set up the database connection (if required)

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

See all articles