Thuta Learning
Linux
IntermediateDevOps & ToolsBeginner

Searching Text with grep

LinuxLesson 18

What you'll walk away with

  • Get comfortable searching text with grep — no need to fear it
  • Practice running the commands yourself in the terminal
  • See how these commands come in handy on a real server or project

Let's think about it this way for a second

grep pattern file finds and prints the lines in file that contain pattern (grep stands for 'global regular expression print' — a confusing name, but simple to use). The -i flag makes the search case-insensitive. The -r flag searches an entire folder, including all sub-folders. The -n flag shows the line number alongside each match — so you instantly know which line an error is on inside a huge file. The -v flag does the opposite — it shows only the lines that don't contain the pattern.

Let's connect this to a real-world scenario

If you just want to see the error lines in a big log file, type grep -n "ERROR" app.log. If you want to find which files across your whole project folder still have leftover TODO comments, grep -rn "TODO" . scans every folder and prints the file name plus line number for each — this is one of the most commonly used commands during code review. Combined with a pipe (from the last chapter), grep also plays a big role in workflows like finding processes with ps aux | grep nginx.

Let's try it together in the terminal

bash
grep "ERROR" app.log
grep -in "error" app.log
grep -rn "TODO" .
grep -v "DEBUG" app.log > errors-only.log
You should see
Lines containing 'ERROR' will show up in the terminal along with their line numbers.

5-Minute Try-It

Write 5 lines in a notes.txt file (put TODO in one of them). Search for it with grep -n TODO notes.txt.

A Quick Word of Caution

If your grep pattern contains special characters (., *, [, etc.), they can automatically be interpreted as regex — if you want to search for a literal dot, you can use grep -F (fixed string).

Easy traps

  • Not quoting the grep pattern, so searching for a phrase with spaces throws an error — you need to wrap it in quotes ("phrase here")
  • Thinking you need -r for a single file instead of a folder (a single file doesn't need -r)

Now Try It Yourself

Write 5 lines in a notes.txt file (put TODO in one of them). Search for it with grep -n TODO notes.txt.

You'll know it worked when: Lines containing 'ERROR' will show up in the terminal along with their line numbers.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Searching Text with grep | Thuta Learning