Linux for Developers Course
Linux for Developers
/
Intermediate

grep

Definition

Global Regular Expression Print. A powerful command-line utility used to search plain-text data sets for lines that match a regular expression or string.

Explain Like I'm New

The 'Ctrl+F' (Find) function for the terminal. You feed it a massive file, tell it what word to look for, and it spits out only the sentences containing that word.

Real World Example

A user complains they can't log in. You type `grep 'username123' auth.log`. Grep scans the massive log file and prints out the exact single line showing 'username123 failed password authentication'.

Common Use Cases

  • •Filtering log files
  • •Finding code snippets
  • •Piping command output

Important `grep` Command Flags

FlagCommandDescription
-i`grep -i 'error' log.txt`Ignore case. Matches 'Error', 'error', and 'ERROR' equally.
-v`grep -v 'warning' log.txt`Invert match. Shows every line that does NOT contain the word.
-r`grep -r 'api_key' /var/www`Recursive. Searches through all files in all subdirectories.
-c`grep -c 'failed' auth.log`Count. Instead of printing the lines, it just prints the total number of matches.
-n`grep -n 'function' app.js`Line number. Prints the exact line number where the match was found.

Interview Questions

basic

  • How do you make `grep` ignore case sensitivity (e.g., matching both 'Error' and 'error')?

intermediate

  • What happens when you pipe another command into grep, like `ls -l | grep 'Feb'`?

Flash Cards

Question

Ignore case?

Click to reveal answer
Answer

Use the `-i` flag: `grep -i 'error' file.txt`.

Question

Piping into grep?

Click to reveal answer
Answer

Instead of searching a file, `grep` filters the live output of the `ls` command. It will only print the files that were modified in February, effectively filtering the list.