0Pricing
Linux Command Line Mastery · 课时

使用 `grep` 过滤文本

掌握 `grep`,利用强大的模式匹配功能过滤文件或命令输出中的文本。

使用 `grep` 过滤文本 是 CoddyKit 上的免费 Linux Command Line Mastery 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Linux Command Line Mastery 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Linux Command Line Mastery 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is `grep`?

Welcome to the world of text filtering! In this lesson, we'll master the mighty grep command.

grep stands for Global Regular Expression Print. It's a powerful command-line utility for searching plain-text data sets for lines that match a regular expression.

  • It helps you quickly find specific information in files.
  • It filters output from other commands.
  • It's indispensable for system administration, programming, and data analysis.

Your First `grep` Search

The most basic use of grep is to search for a specific word or pattern within a file.

The general syntax is: grep "pattern" filename

Let's find all lines containing the word "error" in a log file. Imagine my_log.txt contains various system messages.

echo "System started.
Error: Disk full.
Warning: Low memory.
Error: Network down." > my_log.txt
grep "Error" my_log.txt

Searching Multiple Files

grep isn't limited to a single file. You can search across multiple files or even all files in a directory.

To search multiple files, simply list them after the pattern. To search all files in the current directory, use a wildcard like *.

Let's search for "failed" in all .log files.

echo "Login success" > auth.log
echo "Login failed" > secure.log
echo "System OK" > kernel.log
grep "failed" *.log

Case-Insensitive Search (`-i`)

By default, grep is case-sensitive. This means "Error" is different from "error" or "ERROR".

To perform a case-insensitive search, use the -i option (for ignore-case).

Try finding all instances of "apple", regardless of how it's capitalized.

echo "Apple is good.
I like apples.
APPLES are red." > fruit.txt
grep -i "apple" fruit.txt

Finding What DOESN'T Match (`-v`)

Sometimes you want to see all lines that *do not* contain a specific pattern. This is called an inverted match.

The -v option (for invert-match) does exactly this. It shows all lines that *don't* match the given pattern.

Let's filter out lines that contain "comment" from a script.

echo "# This is a comment
print("Hello")
# Another comment
x = 10" > script.py
grep -v "#" script.py

Counting Occurrences (`-c`)

Instead of showing the matching lines, you might just want to know how many lines match your pattern.

The -c option (for count) tells grep to print only a count of the lines that match the pattern.

How many lines contain "warning" in our system log?

echo "Info: System started.
Warning: Low disk space.
Info: User logged in.
Warning: High CPU usage." > system.log
grep -c "Warning" system.log

Locating Matches with Line Numbers (`-n`)

When you're debugging or analyzing a large file, knowing the exact line number where a match occurs can be very helpful.

The -n option (for line-number) displays the line number before each matching line.

Let's find the line numbers for "function" in a program file.

echo "def setup():
  print("Setting up")
def run_function():
  pass
# Main part" > program.py
grep -n "function" program.py

`grep` with Standard Input

One of grep's most powerful features is its ability to work with pipes (|).

You can pipe the output of one command as input to grep, allowing you to filter command output in real-time.

Let's list all files and then filter to show only those ending with .txt.

touch report.txt document.pdf image.jpg notes.txt
ls -l | grep ".txt"

`grep` Quick Check

You've learned several useful grep options. Let's test your understanding!

Consider a file named server.log which contains messages like "ERROR", "Error", "info", etc.

Recap: Filtering with `grep`

Great job! You've mastered the fundamentals of grep for filtering text.

Here's a quick summary of what we covered:

  • grep "pattern" filename: Basic search for a pattern in a file.
  • grep "pattern" *.log: Search across multiple files using wildcards.
  • -i: Ignore case during the search.
  • -v: Invert the match, showing lines that *don't* contain the pattern.
  • -c: Count the number of matching lines.
  • -n: Display line numbers for matching lines.
  • Piping with |: Filter output from other commands.

These options make grep an incredibly versatile tool for extracting and analyzing information on the command line. Keep practicing!

常见问题解答

「使用 `grep` 过滤文本」课时是免费的吗?

是的 — 「使用 `grep` 过滤文本」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Linux Command Line Mastery 课程的其余内容,请升级到 CoddyKit PRO。 Linux Command Line Mastery 课程共包含 4 节课。

「使用 `grep` 过滤文本」这节课中我会学到什么?

掌握 `grep`,利用强大的模式匹配功能过滤文件或命令输出中的文本。 你通过在浏览器中直接运行的动手代码来练习 Linux Command Line Mastery,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Linux Command Line Mastery 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Linux Command Line Mastery 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 `grep` 过滤文本」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Linux Command Line Mastery 课中编写并运行代码吗?

能。每节 Linux Command Line Mastery 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 标准流与重定向
  2. 使用 `grep` 过滤文本
  3. 使用 `sed` 和 `awk` 操作文本
  4. 使用 sort、uniq 和 cut 合并并排序输出
← 返回 Linux Command Line Mastery