grep Commandgrep命令

Search text using pattern matching使用模式匹配搜索文本

What is grep?什么是grep?

grep stands for "Global Regular Expression Print". It's one of the most powerful and commonly used commands for searching text patterns in files. It supports basic and extended regular expressions, making it incredibly versatile for text processing tasks.

grep代表"Global Regular Expression Print"(全局正则表达式打印)。它是用于在文件中搜索文本模式的最强大和最常用的命令之一。它支持基本和扩展的正则表达式,使其在文本处理任务中极其通用。

Basic Usage基本用法

$ grep "error" logfile.txt
# Search for lines containing "error"
$ grep -i "hello" file.txt
# Case-insensitive search
$ grep -r "TODO" .
# Recursively search for "TODO" in current directory
$ grep "error" logfile.txt
# 搜索包含"error"的行
$ grep -i "hello" file.txt
# 不区分大小写搜索
$ grep -r "TODO" .
# 在当前目录中递归搜索"TODO"

Common Options常用选项

Option选项 Full Name完整名称 Description描述 Example示例
-i ignore-case忽略大小写 Case-insensitive matching不区分大小写匹配 grep -i "pattern" file.txt
-v invert-match反向匹配 Select non-matching lines选择不匹配的行 grep -v "comment" file.txt
-n line-number行号 Prefix with line number加上行号前缀 grep -n "error" log.txt
-c count计数 Print count of matching lines打印匹配行的计数 grep -c "TODO" *.py
-r recursive递归 Search recursively递归搜索 grep -r "function" src/
-l files-with-matches包含匹配的文件 Show only filenames仅显示文件名 grep -l "import" *.py
-E extended-regexp扩展正则 Use extended regex使用扩展正则表达式 grep -E "error|warning" log.txt
-w word-regexp单词正则 Match whole words only仅匹配整个单词 grep -w "cat" file.txt
-e regexp正则表达式 Specify pattern (useful with -)指定模式(对以-开头的有用) grep -e "-v" file.txt
-o only-matching仅匹配部分 Show only matched part仅显示匹配的部分 grep -o "[0-9]+" file.txt

Practical Scenarios实际场景

Search for Multiple Patterns搜索多个模式

$ grep -E "error|warning|critical" app.log
# Find lines with any of these keywords
$ grep -E "error|warning|critical" app.log
# 查找包含任何这些关键字的行

Count Pattern Occurrences计算模式出现次数

$ grep -c "function" *.py
# Count functions in each Python file
$ grep -c "function" *.py
# 计算每个Python文件中的函数数量

Filter Out Comments过滤掉注释

$ grep -v "^#" config.txt
# Exclude lines starting with #
$ grep -v "^#" config.txt
# 排除以#开头的行

Search with Regex使用正则表达式搜索

$ grep -E "^[0-9]{3}-[0-9]{4}$" phone.txt
# Find phone numbers like 123-4567
$ grep -E "^[0-9]{3}-[0-9]{4}$" phone.txt
# 查找像123-4567这样的电话号码

Memory Tricks记忆技巧

🔍 "grep" = g/re/p from ed editor - g = global, re = regular expression, p = print

🔍 "grep" = 来自ed编辑器的g/re/p - g = global(全局),re = regular expression(正则表达式),p = print(打印)

🔤 -i = Ignore case - Case doesn't matter

🔤 -i = Ignore case(忽略大小写) - 大小写不重要

🔄 -v = Versa/reVerse - Reverse the match (invert)

🔄 -v = Versa/reVerse(反转) - 反转匹配(取反)

🔢 -n = Number lines - Show line numbers

🔢 -n = Number lines(行号) - 显示行号

📊 -c = Count - Count matches, don't show lines

📊 -c = Count(计数) - 计算匹配项,不显示行

📁 -r = Recursive - Search in subdirectories too

📁 -r = Recursive(递归) - 也在子目录中搜索

🌟 -E = Extended regex - Enable full regex features (OR, groups, etc.)

🌟 -E = Extended regex(扩展正则) - 启用完整的正则表达式功能(OR、分组等)