search

Introduction to Linux command grep

Sep 04, 2017 pm 02:12 PM
greplinuxintroduce

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 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:

\ 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

\

\> 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 '\' 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
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
The 5 Core Components of the Linux Operating SystemThe 5 Core Components of the Linux Operating SystemMay 08, 2025 am 12:08 AM

The five core components of the Linux operating system are: 1. Kernel, 2. System libraries, 3. System tools, 4. System services, 5. File system. These components work together to ensure the stable and efficient operation of the system, and together form a powerful and flexible operating system.

The 5 Essential Elements of Linux: ExplainedThe 5 Essential Elements of Linux: ExplainedMay 07, 2025 am 12:14 AM

The five core elements of Linux are: 1. Kernel, 2. Command line interface, 3. File system, 4. Package management, 5. Community and open source. Together, these elements define the nature and functionality of Linux.

Linux Operations: Security and User ManagementLinux Operations: Security and User ManagementMay 06, 2025 am 12:04 AM

Linux user management and security can be achieved through the following steps: 1. Create users and groups, using commands such as sudouseradd-m-gdevelopers-s/bin/bashjohn. 2. Bulkly create users and set password policies, using the for loop and chpasswd commands. 3. Check and fix common errors, home directory and shell settings. 4. Implement best practices such as strong cryptographic policies, regular audits and the principle of minimum authority. 5. Optimize performance, use sudo and adjust PAM module configuration. Through these methods, users can be effectively managed and system security can be improved.

Linux Operations: File System, Processes, and MoreLinux Operations: File System, Processes, and MoreMay 05, 2025 am 12:16 AM

The core operations of Linux file system and process management include file system management and process control. 1) File system operations include creating, deleting, copying and moving files or directories, using commands such as mkdir, rmdir, cp and mv. 2) Process management involves starting, monitoring and killing processes, using commands such as ./my_script.sh&, top and kill.

Linux Operations: Shell Scripting and AutomationLinux Operations: Shell Scripting and AutomationMay 04, 2025 am 12:15 AM

Shell scripts are powerful tools for automated execution of commands in Linux systems. 1) The shell script executes commands line by line through the interpreter to process variable substitution and conditional judgment. 2) The basic usage includes backup operations, such as using the tar command to back up the directory. 3) Advanced usage involves the use of functions and case statements to manage services. 4) Debugging skills include using set-x to enable debugging mode and set-e to exit when the command fails. 5) Performance optimization is recommended to avoid subshells, use arrays and optimization loops.

Linux Operations: Understanding the Core FunctionalityLinux Operations: Understanding the Core FunctionalityMay 03, 2025 am 12:09 AM

Linux is a Unix-based multi-user, multi-tasking operating system that emphasizes simplicity, modularity and openness. Its core functions include: file system: organized in a tree structure, supports multiple file systems such as ext4, XFS, Btrfs, and use df-T to view file system types. Process management: View the process through the ps command, manage the process using PID, involving priority settings and signal processing. Network configuration: Flexible setting of IP addresses and managing network services, and use sudoipaddradd to configure IP. These features are applied in real-life operations through basic commands and advanced script automation, improving efficiency and reducing errors.

Linux: Entering and Exiting Maintenance ModeLinux: Entering and Exiting Maintenance ModeMay 02, 2025 am 12:01 AM

The methods to enter Linux maintenance mode include: 1. Edit the GRUB configuration file, add "single" or "1" parameters and update the GRUB configuration; 2. Edit the startup parameters in the GRUB menu, add "single" or "1". Exit maintenance mode only requires restarting the system. With these steps, you can quickly enter maintenance mode when needed and exit safely, ensuring system stability and security.

Understanding Linux: The Core Components DefinedUnderstanding Linux: The Core Components DefinedMay 01, 2025 am 12:19 AM

The core components of Linux include kernel, shell, file system, process management and memory management. 1) Kernel management system resources, 2) shell provides user interaction interface, 3) file system supports multiple formats, 4) Process management is implemented through system calls such as fork, and 5) memory management uses virtual memory technology.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.