Fundamentals 4 min read

Mastering grep: Powerful Text Search Techniques for Linux

This guide explains grep's purpose, syntax, key options, and provides practical examples—including case‑insensitive, inverse, recursive, and anchored searches—to help users efficiently locate text in files on Unix-like systems.

Open Source Linux
Open Source Linux
Open Source Linux
Mastering grep: Powerful Text Search Techniques for Linux

grep: Text Search Tool

Function Description

grep is a powerful text‑search utility that uses regular expressions to search files and prints matching lines.

The Unix grep family includes grep, egrep, and fgrep. egrep is an extended version (equivalent to grep -E) supporting additional regex metacharacters, while fgrep (fast grep, grep -F) matches fixed strings without regex.

Command Syntax

grep [options] [pattern] [file]

Option Meanings

-c : count the number of matching lines.

-i : ignore case distinctions.

-l : list only the names of files with matches.

-n : show line numbers of matching lines.

-v : invert match, show lines that do not match.

-x : force the pattern to match the whole line.

-w : force the pattern to match whole words.

-q : suppress output; exit status indicates success.

-s : suppress error messages.

-r : recursive search.

Parameter Examples

Example 1 – Find a string

# grep mysql /etc/passwd
mysql:x:1001:1001::/home/mysql:/sbin/nologin

# grep -n mysql /etc/passwd
22:mysql:x:1001:1001::/home/mysql:/sbin/nologin

Example 2 – Inverse search

# grep -v nologin /etc/passwd

Example 3 – Recursive search

# grep -r "开源Linux" /test
/test/readme.txt:欢迎关注微信公众号:开源Linux,收获每日技术干货。

# grep -r -l "开源Linux" /test
/test/readme.txt

Example 4 – Line start/end anchors

# grep ^my /etc/passwd
mysql:x:1001:1001::/home/mysql:/sbin/nologin

# grep -n nologin$ /etc/passwd
... (line number shown)

# grep -v ^$ readme.txt
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

regexGreptext search
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.