Mastering grep: Essential Syntax, Options, and Real-World Examples
This guide explains the Linux grep command, covering its core syntax, most useful options, and a dozen practical regular‑expression examples that demonstrate how to search, filter, and manipulate text files efficiently from the command line.
grep (Global Regular Expression Print) is a powerful Linux utility for searching text using regular expressions and printing matching lines. It is available to all users and is a fundamental tool for command‑line text processing.
Basic syntax : grep [options] pattern [file...] Common options : -c: output only the count of matching lines. -i: ignore case distinctions. -h: suppress file name output when searching multiple files. -l: list only the names of files containing matches. -n: show line numbers of matches. -s: suppress error messages for nonexistent or unreadable files. -v: invert match, showing lines that do not match. --color=auto: highlight matched text.
Practical examples :
Find lines containing "png": grep -n 'png' linuxmi.py Find lines not containing "png": grep -vn 'png' linuxmi.py Match strings where "na" is not preceded by "v": grep -n '[^v]na' linuxmi.py Match strings where "na" is not preceded by any lowercase letter: grep -n '[^a-z]na' linuxmi.py Find lines starting with "ba": grep -n '^ba' linuxmi.py Find lines not starting with a letter: grep -n '^[^a-zA-Z]' linuxmi.py Find lines ending with a period: grep -n '\.$' linuxmi.py Match any two characters between "l" and "k": grep -n 'l..k' linuxmi.py Find lines containing consecutive "e" characters: grep -n 'eee*' linuxmi.py Find lines starting with "l", ending with "e", and containing at least one "x" in between: grep -n 'lxx*e' linuxmi.py Find lines starting with "l" and ending with "k", with any characters (or none) in between: grep -n 'l.*k' linuxmi.py Match exactly two consecutive "e" characters using a quantifier: grep -n 'e\{2\}' linuxmi.py Note: Characters like "." and "*" have special meanings in regular expressions and must be escaped (e.g., "\\.") when you need to match them literally.
Original article: https://urlify.cn/zaYrei
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
