← 返回命令列表

Linux command

grep 命令

文件

复制后可按需替换文件名、目录或参数。

常用示例

Search for pattern in file

grep [pattern] [file]

Case insensitive search

grep -i [pattern] [file]

Recursive search in directory

grep -r [pattern] [directory]

Show line numbers

grep -n [pattern] [file]

Invert match (exclude pattern)

grep -v [pattern] [file]

Extended regex

grep -E '[regex]' [file]

Show only filenames containing matches

grep -rl [pattern] [directory]

Count matches

grep -c [pattern] [file]

Search with context (3 lines before and after)

grep -C 3 [pattern] [file]

Search recursively but only in specific file types

grep -r --include='[*.py]' [pattern] [directory]

说明

grep searches files for lines matching a regular expression pattern. It is one of the most fundamental Unix utilities, named for g/re/p (global regular expression print) from the ed editor. The tool supports basic and extended regular expressions, recursive directory searching, and various output formats. It can search multiple files, show context around matches, and highlight results with color.

参数

-i, --ignore-case
Case insensitive matching.
-v, --invert-match
Select non-matching lines.
-r, --recursive
Search directories recursively.
-n, --line-number
Show line numbers.
-c, --count
Print match count only.
-l, --files-with-matches
Print only filenames.
-E, --extended-regexp
Use extended regex.
-F, --fixed-strings
Match literal strings.
-o, --only-matching
Print only matched parts.
-A _NUM_
Print NUM lines after match.
-B _NUM_
Print NUM lines before match.
-C _NUM_
Print NUM lines of context.
-P, --perl-regexp
Use Perl-compatible regular expressions (PCRE).
-w, --word-regexp
Match only whole words.
-q, --quiet, --silent
Suppress output; exit with 0 if match found.
--include _GLOB_
Search only files matching the glob pattern.
--exclude _GLOB_
Skip files matching the glob pattern.
--color
Highlight matches.
--help
Display help information.

FAQ

What is the grep command used for?

grep searches files for lines matching a regular expression pattern. It is one of the most fundamental Unix utilities, named for g/re/p (global regular expression print) from the ed editor. The tool supports basic and extended regular expressions, recursive directory searching, and various output formats. It can search multiple files, show context around matches, and highlight results with color.

How do I run a basic grep example?

Run `grep [pattern] [file]` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

What does -i, --ignore-case do in grep?

Case insensitive matching.