Ravindra BagaleCourses & study guides मराठी Track your progress

Linux grep Command and Regular Expressions (Regex) Tutorial with Examples

grep finds lines that match a pattern. A regular expression (regex) is the pattern language: it lets you say 'a line that starts with ERROR', 'any IP address' or 'a word of 3 to 5 digits'. grep plus regex is the single most used skill when you debug servers, search code or audit security.

What you'll learn in this chapter

  • Search text with grep and its key options
  • Search folders recursively and list files
  • Show context around matches
  • Write basic regex: anchors, dot, classes, star
  • Use extended regex: + ? {n,m} | ( )
  • Use grep -o, -P, fixed strings and ripgrep

1. An everyday example: finding a name in a phone book

Why do we need this?

Meera's father has an old diary with 2,000 phone numbers. She wants: every line with 'Joshi', but not 'Joshi Travels'; names starting with 'D'; numbers that start with 98; and the two lines below 'Doctor' because the clinic timing is written there.

What is it?

Lines with Joshi = grep Joshi. Not Travels = grep -v Travels. Names starting with D = grep '^D'. Numbers starting 98 = grep -E '\b98[0-9]{8}\b'. Two lines below = grep -A2 Doctor.

How to do it (step by step)

How grep decidesRead one lineTry the pattern at every positionMatch found? Print the line (or not, with -v)Add options: -n number, -c count, -o only matchMove to the next lineExit 0 if anything matched, 1 if none
grep works line by line, so a pattern never crosses a new line (unless -z).

2. grep basics: the options you use daily

Why do we need this?

Logs and configs are huge. You need the few lines that matter in a second.

What is it?

grep PATTERN FILE prints matching lines. -i ignore case, -v invert (non-matching), -n line numbers, -c count lines, -w whole word only, -x whole line only, -o print only the matched part, -m N stop after N matches, -q quiet (just the exit code), -h/-H hide/show file names, --color=auto highlight. Quote the pattern in single quotes so the shell does not change it.

OptionMeaning
-iIgnore case
-vLines that do NOT match
-nShow line numbers
-cCount matching lines
-wMatch whole words
-oOnly the matched text
-qQuiet, exit code only
-m NStop after N matches

How to do it (step by step)

  1. Find errors.
grep ERROR app.log

Output:

10:12:44 ERROR payment timeout order=8812
10:15:02 ERROR db connection refused

What it means: Only lines with ERROR.

  1. Ignore case and number lines.
grep -in 'timeout' app.log

Output:

57:10:12:44 ERROR payment timeout order=8812
90:10:20:11 WARN Timeout on cache

What it means: 57 and 90 are line numbers.

  1. Hide comments and empty lines of a config.
grep -v '^#' /etc/ssh/sshd_config | grep -v '^$'

Output:

Port 22
PermitRootLogin no
PasswordAuthentication no

What it means: -v inverts. Now you see only real settings.

  1. Whole word only.
grep -w 'root' /etc/passwd

Output:

root:x:0:0:root:/root:/bin/bash

What it means: -w skips words like chroot or rootless.

  1. Count failed logins.
sudo grep -c 'Failed password' /var/log/secure

Output:

143

What it means: 143 lines matched.

  1. Use grep in an if.
if grep -q '^ravi:' /etc/passwd; then echo exists; fi

Output:

exists

What it means: -q prints nothing; exit code 0 means found.

  1. Many patterns at once.
grep -e ERROR -e FATAL app.log | wc -l

Output:

31

What it means: -e can be repeated. Or put patterns in a file and use -f.

3. Search many files and folders

Why do we need this?

Where is this setting defined? Which file has the old password? You must search a whole folder tree.

What is it?

grep -r PATTERN DIR searches all files under DIR (-R also follows symlinks). -l lists only file names with matches, -L files without matches. --include='*.conf' and --exclude-dir=.git filter files. -I skips binary files. zgrep searches .gz files.

How to do it (step by step)

  1. Find where a port is set.
grep -rn 'listen 443' /etc/nginx/

Output:

/etc/nginx/conf.d/shop.conf:5:    listen 443 ssl;

What it means: File, line number and the line.

  1. Only file names.
grep -rl 'DB_PASSWORD' /srv/app

Output:

/srv/app/.env
/srv/app/config/old.env

What it means: Good to find secrets left in files.

  1. Only some file types.
grep -rn --include='*.py' 'import boto3' ~/projects

Output:

/home/ravi/projects/s3sync/main.py:3:import boto3

What it means: Skips everything that is not .py.

  1. Skip .git and node_modules.
grep -rn --exclude-dir={.git,node_modules} 'TODO' .

Output:

./src/cart.js:41: // TODO handle coupon

What it means: Faster and less noise.

  1. Search rotated gz logs.
zgrep -c 'Out of memory' /var/log/messages*.gz

Output:

/var/log/messages-1.gz:2
/var/log/messages-2.gz:0

What it means: No unzip needed.

  1. Files that do NOT contain a header.
grep -L 'Copyright' src/*.c

Output:

src/new_feature.c

What it means: -L lists files without a match.

4. Context: lines before and after

Why do we need this?

An error line alone rarely tells the story. The lines before it show the cause; the lines after show the stack trace.

What is it?

-A N shows N lines after each match, -B N before, -C N both sides. Groups are separated by --. Combine with -n to know where you are.

How to do it (step by step)

  1. Stack trace after an exception.
grep -A3 'Exception' app.log

Output:

10:20:11 ERROR NullPointerException
    at Cart.total(Cart.java:42)
    at Checkout.pay(Checkout.java:17)
    at Api.post(Api.java:88)

What it means: Three lines after the match.

  1. What happened before a crash.
grep -B2 'Killed process' /var/log/messages

Output:

kernel: Out of memory: Killed process 3112 (java)

What it means: -B shows the lines leading up to it.

  1. Both sides with line numbers.
grep -n -C1 'disk full' backup.log

Output:

41-starting upload
42:ERROR disk full
43-retry in 60s

What it means: Matches use :, context lines use -.

5. Basic regex: anchors, dot, classes and star

Why do we need this?

Plain words are not enough. You need 'starts with', 'ends with', 'any digit' or 'any character here'.

What is it?

^ start of line, $ end of line, . any one character, [abc] one of a, b, c, [^abc] none of them, [0-9] a digit, [A-Za-z] a letter, * zero or more of the previous item, .* anything. POSIX classes: [[:digit:]] [[:alpha:]] [[:space:]] [[:upper:]]. \ escapes a special character: \. is a real dot. \b or \< \> mark word edges in GNU grep.

SymbolMeansExample
^Start of line^ERROR
$End of line\.conf$
.Any one characterh.t
[0-9]One digit[0-9][0-9]
[^ ]Not a space[^ ]*
*0 or more of previousab*c
\Escape special char1\.5
\bWord edge\bcat\b

How to do it (step by step)

  1. Lines that start with ERROR.
grep '^ERROR' worker.log

Output:

ERROR job 77 failed

What it means: ^ ties the match to the start.

  1. Lines ending in .conf.
ls /etc | grep '\.conf$' | head -3

Output:

host.conf
ld.so.conf
resolv.conf

What it means: \. is a real dot; $ is the end.

  1. Empty lines.
grep -c '^$' notes.txt

Output:

6

What it means: ^$ means nothing between start and end.

  1. Any character with dot.
echo -e 'hat\nhot\nheat' | grep 'h.t'

Output:

hat
hot

What it means: One character between h and t. 'heat' has two.

  1. HTTP 4xx or 5xx codes.
grep ' [45][0-9][0-9] ' access.log | head -2

Output:

10.0.0.7 GET /cart 404 0
10.0.0.2 POST /pay 503 0

What it means: A class [45] then two digits.

  1. Lines without any digit.
grep -v '[0-9]' list.txt

Output:

apple
banana

What it means: -v with a digit class.

  1. Uppercase words only with a POSIX class.
grep -o '\b[[:upper:]][[:upper:]]*\b' notes.txt | sort -u

Output:

AWS
EC2

What it means: Works in any language setting.

6. Extended regex: + ? {n,m} | and groups

Why do we need this?

To match IPs, emails, phone numbers or 'this OR that', you need repeat counts and choices.

What is it?

grep -E (or egrep, now deprecated) turns on extended regex. + one or more, ? zero or one, {3} exactly 3, {2,4} 2 to 4, {2,} 2 or more, a|b either, ( ) groups. In basic grep the same need backslashes: \+ \? \{3\} \| \( \). grep -P uses Perl regex with \d, \w, \s, lazy .*? and lookarounds.

Symbol (-E)Means
+1 or more
?0 or 1 (optional)
{3}Exactly 3
{2,4}2 to 4
a|ba or b
( )Group

How to do it (step by step)

  1. ERROR or FATAL.
grep -E 'ERROR|FATAL' app.log | wc -l

Output:

31

What it means: | means or. Needs -E.

  1. Find IPv4 addresses.
grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' auth.log | sort -u | head -3

Output:

10.0.0.5
49.36.12.4
103.21.8.77

What it means: A group of 1-3 digits and a dot, 3 times, then 1-3 digits.

  1. Indian mobile numbers.
grep -Eo '\b[6-9][0-9]{9}\b' contacts.txt

Output:

9822012345
7020011122

What it means: Starts with 6-9, then 9 more digits.

  1. Emails.
grep -Eio '[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}' users.txt

Output:

aditi@example.com
john.doe@mail.co.uk

What it means: + means one or more allowed characters.

  1. Optional letter.
grep -E 'colou?r' notes.txt

Output:

color
colour

What it means: u? may or may not be there.

  1. Perl regex: the value after order=.
grep -oP 'order=\K\d+' app.log | head -2

Output:

8812
8813

What it means: \K drops what came before from the output; \d is a digit.

  1. Same pattern in basic grep.
grep 'ERROR\|FATAL' app.log | wc -l

Output:

31

What it means: In basic regex | needs a backslash.

7. Fixed strings, speed and ripgrep

Why do we need this?

Searching for a string full of dots or brackets, or millions of lines, needs the fast and safe way.

What is it?

grep -F (fgrep) treats the pattern as plain text: no regex, faster and no escaping. -f file reads many patterns from a file. LC_ALL=C grep is much faster on big ASCII logs. ripgrep (rg) is a modern recursive grep: fast, respects .gitignore, shows colour and line numbers by default. ag and ack are similar tools.

How to do it (step by step)

  1. Search a string with dots safely.
grep -F '10.0.0.1' access.log | head -1

Output:

10.0.0.1 GET /p1 200

What it means: Without -F, . would match any character (10x0y0z1).

  1. Block list from a file.
grep -Ff bad_ips.txt access.log | wc -l

Output:

57

What it means: Each line of bad_ips.txt is a pattern.

  1. Speed up on a big log.
time LC_ALL=C grep -c 'ERROR' big.log

Output:

120334
real 0m0.41s

What it means: C locale avoids slow Unicode rules.

  1. ripgrep in a code repo.
rg -n 'boto3.client' --type py

Output:

src/sync.py
3:s3 = boto3.client('s3')

What it means: rg skips .gitignore files and is recursive by default.

8. Real examples from many industries

Why do we need this?

The same Linux skill shows up in every kind of company. Seeing it in many places helps you remember it.

What is it?

Each row is a made-up team. It shows who uses this and how.

How to do it (step by step)

Team and cityHow they use itCommand
Vikram, SOC analyst, GurugramFinds brute-force IPs in SSH logsgrep 'Failed password' /var/log/secure | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | sort | uniq -c | sort -nr
Hannah, fintech, ZurichChecks no card numbers are in logsgrep -rEn '\b[0-9]{16}\b' /var/log/app
Omar, airline ops, DohaShows context around booking failuresgrep -C3 'PNR_FAIL' booking.log
Kavya, QA, PuneFails a CI build if TODO is left in code! grep -rn 'TODO' src/
Mateo, e-commerce, Buenos AiresCounts 5xx errors per minutegrep -E '" 5[0-9]{2} ' access.log | cut -c14-30 | uniq -c
Yuki, platform, OsakaFinds which config sets a timeoutgrep -rn --include='*.yaml' 'timeout:' k8s/

9. Common errors and how to fix them

Why do we need this?

Everyone hits these errors. Knowing the cause saves hours.

What is it?

Read the exact message first. Then match it to a row below.

How to do it (step by step)

Error you seeWhy it happensHow to fix
grep: app.log: No such file or directoryWrong file pathCheck the path with ls.
ls /var/log/app/
grep: /var/log/secure: Permission deniedFile readable only by rootUse sudo.
sudo grep sshd /var/log/secure
grep: Unmatched ( or \(Bracket in pattern not closed or not escapedEscape it or use -F for plain text.
grep -F 'f(x)' code.c
grep: Invalid range endA range like [z-a] or locale issueWrite ranges low to high or use classes.
grep '[[:alpha:]]' f
Binary file app.bin matchesgrep found a match in a binary fileUse -a to treat as text, or -I to skip binaries.
grep -a 'version' app.bin
Pattern with | matches nothing| needs -E (or \| in basic regex)Add -E.
grep -E 'a|b' f
grep -r is very slowSearching .git, node_modules or huge binariesExclude folders or use rg.
grep -r --exclude-dir=node_modules x .
grep: warning: egrep is obsolescentegrep and fgrep are deprecatedUse grep -E and grep -F.
grep -E 'x|y' f
Pattern with $ matches wrongDouble quotes let the shell expand $VARUse single quotes.
grep 'price$' f
grep -P: unsupported on this systemBusyBox or macOS grep has no -PUse -E, or install GNU grep / ripgrep.
grep -Eo 'order=[0-9]+' f

10. Troubleshooting step by step

Why do we need this?

When grep finds nothing (or too much), test the pattern on a tiny sample first.

What is it?

Go top to bottom. Stop at the first step that shows the problem.

How to do it (step by step)

  1. Is the text really there? Use plain -F first.
grep -F -c 'timeout' app.log
  1. Case issue? Add -i.
grep -ic 'timeout' app.log
  1. Test the regex on one echo line.
echo 'order=8812 ok' | grep -Eo 'order=[0-9]+'
  1. Hidden characters (\r, tabs) in the file?
grep -m1 'timeout' app.log | cat -A
  1. Is it binary or compressed?
file app.log
  1. Check the exit code.
grep -q x app.log; echo $?

11. Lab 1: Hunt an SSH brute-force attack

Why do we need this?

Use grep and regex to find who is attacking, how often, and which users they try.

What is it?

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

How to do it (step by step)

  1. Create a sample auth log.
mkdir -p ~/lab9 && cd ~/lab9 && for i in $(seq 1 60); do echo "Oct 25 10:$((i%60)):01 web sshd[9$i]: Failed password for $([ $((i%3)) = 0 ] && echo invalid user admin || echo root) from 49.36.12.$((i%4)) port 5$i ssh2"; done > auth.log; echo 'Oct 25 11:00:00 web sshd[1]: Accepted publickey for ravi from 10.0.0.5' >> auth.log

Output:

(no output)
  1. Count failures.
grep -c 'Failed password' auth.log

Output:

60
  1. Extract the attacking IPs and count them.
grep 'Failed' auth.log | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | sort | uniq -c | sort -nr

Output:

     15 49.36.12.0
     15 49.36.12.1
     15 49.36.12.2
     15 49.36.12.3
  1. Which users were tried?
grep -oP 'for (invalid user )?\K\w+' auth.log | sort | uniq -c

Output:

     20 admin
     40 root
      1 ravi
  1. Show the good login with context.
grep -B1 'Accepted' auth.log

Output:

Oct 25 10:0:01 web sshd[960]: Failed password for invalid user admin ...
Oct 25 11:00:00 web sshd[1]: Accepted publickey for ravi from 10.0.0.5

12. Lab 2: Audit a code folder for secrets

Why do we need this?

Search recursively with include and exclude rules and list risky files.

What is it?

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

How to do it (step by step)

  1. Make a small project.
cd ~/lab9 && mkdir -p proj/src proj/.git && echo 'AWS_SECRET=abc123' > proj/src/.env && echo 'print(1)' > proj/src/a.py && echo 'AWS_SECRET=old' > proj/.git/x

Output:

(no output)
  1. Search everything.
grep -rn 'AWS_SECRET' proj

Output:

proj/src/.env:1:AWS_SECRET=abc123
proj/.git/x:1:AWS_SECRET=old
  1. Skip .git and list file names only.
grep -rl --exclude-dir=.git 'AWS_SECRET' proj

Output:

proj/src/.env
  1. Find AWS access key id patterns.
echo 'key=AKIAIOSFODNN7EXAMPLE' >> proj/src/a.py; grep -rEon 'AKIA[0-9A-Z]{16}' proj/src

Output:

proj/src/a.py:2:AKIAIOSFODNN7EXAMPLE

Ravindra Bagale's Tip

Always put grep patterns in single quotes, and test a new regex with echo on one sample line before running it on a 5 GB log. It saves time and avoids shell surprises.

13. Frequently asked questions

Q. What is the difference between grep, grep -E and grep -F?

grep uses basic regex, -E extended regex (+ ? | {} without backslashes), -F plain text with no regex.

Q. Why does grep . match everything?

A dot means any character. Use \. or -F for a real dot.

Q. How do I search for a word starting with a dash?

Use -e or --: grep -e '-v' file.

Q. Does grep search across lines?

No, it works line by line. Use grep -z or -P with (?s), or awk/sed for multi-line.

Q. What does the exit code of grep mean?

0 match found, 1 no match, 2 error.

Q. Is regex the same as shell globs?

No. In globs * means anything; in regex * means 'repeat the previous item'. .* is the regex 'anything'.

Q. Should I use ripgrep?

For code search on your laptop, yes. On servers, grep is always installed, so learn grep first.

Q. How do I show only the matching text?

grep -o.

14. Interview questions and answers

Beginner level

Q. How do you search a word ignoring case?

grep -i word file.

Q. How do you show lines that do not match?

grep -v pattern file.

Q. How do you search all files in a folder?

grep -r pattern folder/ (add -n for line numbers).

Q. What do ^ and $ mean?

Start and end of a line.

Mid level level

Q. Show 5 lines after each match.

grep -A5 pattern file.

Q. Extract all IP addresses from a log.

grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' file.

Q. List only files that contain a string.

grep -rl string dir.

Q. Show config lines without comments and blanks.

grep -Ev '^\s*(#|$)' file.

Senior level

Q. grep on a 30 GB log is slow. How do you speed it up?

LC_ALL=C, -F for fixed strings, anchor the pattern, -m to stop early, search only the time window (sed/awk ranges), parallel over rotated files, or ripgrep.

Q. Basic vs extended vs PCRE regex?

BRE needs \ before + ? | {} (). ERE (-E) does not. PCRE (-P) adds \d \w, lazy quantifiers, lookahead/behind and \K.

Q. How would you block a CI merge that adds secrets?

A pre-commit or CI step: git diff --cached | grep -E 'AKIA[0-9A-Z]{16}|BEGIN RSA PRIVATE' and fail on exit 0; better, use gitleaks or trufflehog.

Q. Why might grep -c and grep -o | wc -l give different numbers?

-c counts lines with a match; -o prints each match, so a line with 3 matches counts 3.

Try at home

  1. Make a file with 10 lines of your contacts (name and phone). Use grep -E to find numbers starting with 9, and grep -c to count names with 'a'.
  2. Run 'grep -v ^# /etc/ssh/sshd_config | grep -v ^$' on any Linux box and list the real settings you see.

Practice Tasks

About this scenario

London Legal LLP is a law business in London. Oliver Hughes looks after its IT and cloud work. They count money in GBP and run their AWS resources in the eu-west-2 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy Search ignoring case

Why: Error, ERROR and error all matter.

What to do: Find lines with the word error in any case in app.log.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Show line numbers

Why: Jump to the right line in vim.

What to do: Search for timeout in app.log and show line numbers.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Hide comment lines

Why: See only active settings.

What to do: Print lines of sshd_config that do NOT start with #. Use the pattern '^#'.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Count matching lines

Why: How many 500 errors?

What to do: Count lines containing " 500 " in access.log using only grep. Use the pattern ' 500 '.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Regex end anchor

Why: Match the end of a line.

What to do: Which single regex character means end of line?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Search a whole project

Why: Where is the DB password used?

What to do: Search recursively for DB_PASS in the folder src and show line numbers.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Only file names

Why: You only need which files to edit.

What to do: List only the names of files under conf that contain listen, recursively.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Whole word only

Why: cat should not match category.

What to do: Find lines with the whole word cat in pets.txt.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Lines after a match

Why: Stack traces follow the error line.

What to do: Show each Exception line in app.log plus 5 lines after it.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Context around a match

Why: See what happened around a crash.

What to do: Show 3 lines before and after each OOM line in kern.log.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Lines starting with a word

Why: Pick only real directives.

What to do: Show lines in nginx.conf that start with server. Use the anchor in quotes.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Search a literal string

Why: Dots and stars are not regex here.

What to do: Search for the exact text 1.2.3.* in rules.txt treating it as a fixed string. Quote it.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Find a process

Why: Is nginx running?

What to do: List all processes with ps aux and filter lines with nginx.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Match two words

Why: Find both kinds of failures.

What to do: Using extended regex, find lines in api.log with WARN or CRIT. Pattern 'WARN|CRIT'.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Extract only IPs

Why: Build a list of client IPs.

What to do: Print only the matching IPv4 parts from access.log using -oE and the pattern '[0-9]+(\.[0-9]+){3}'.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Search only some file types

Why: Skip node_modules noise.

What to do: Recursively search for TODO in the current folder (.) but only in *.py files. Use --include='*.py'.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

In short

  1. grep -i -v -n -c -w -o -q are daily options.
  2. grep -rn searches folders; -l lists files; --include and --exclude-dir filter.
  3. -A -B -C show context.
  4. Basic regex: ^ $ . [ ] * \.
  5. grep -E adds + ? {n,m} | ( ); -P adds \d \K lookarounds.
  6. -F for plain text; rg for fast code search.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

grep in 4 steps. Find text in files and logs. -i case, -n line no, -v invert. -r whole folder, -l names only. Find a setting in a project.
Revision card: grep in 4 steps · Download PNG · Open card page
Regex cheat card. Match patterns, not just words. ^ start, $ end, . any, * repeat. -E for + ? | {n} and groups. Extract IPs only.
Revision card: Regex cheat card · Download PNG · Open card page
grep vs grep -E. Basic regex. / Extended regex.
Comparison: grep vs grep -E · Download PNG · Open card page
grep vs ripgrep (rg). On every Linux box. / Install it yourself.
Comparison: grep vs ripgrep (rg) · Download PNG · Open card page
grep finds itself in ps?. grep line has the word too. Use a bracket trick or pgrep. Clean process check.
Interview card: grep finds itself in ps? · Download PNG · Open card page
grep two words at once?. Basic grep treats | as text. Use -E for alternation. ERROR or FATAL.
Interview card: grep two words at once? · Download PNG · Open card page
Fast search in huge repos?. Skip folders you do not need. Use --include, -F or rg. Only Python files.
Interview card: Fast search in huge repos? · Download PNG · Open card page
See lines around an error?. One line hides the cause. -A after, -B before, -C both. 3 lines each side.
Interview card: See lines around an error? · Download PNG · Open card page

More cards: Ravi Sir's Cards.