Skip to content

The grep command

Print lines that match a pattern. Searches each file (or what is piped into it) and prints the lines that contain PATTERN. The pattern is a basic regular expression: plain words work as you would expect, . matches any character, ^ means the start of the line and $ the end. Quote patterns that contain spaces or special characters.

Usage

grep [OPTION]... PATTERN [FILE]...

Options

-i, --ignore-casematch upper and lower case alike
-n, --line-numbershow the line number of each match
-v, --invert-matchprint the lines that do NOT match
-c, --countprint how many lines match, instead of the lines
-r, -R, --recursivesearch every file in a directory and the folders inside it
-l, --files-with-matchesprint only the names of files that have a match
-w, --word-regexpmatch whole words only
-o, --only-matchingprint only the matching part of each line
-E, --extended-regexpextended regular expressions: + ? | and ( ) work without backslashes
-F, --fixed-stringstreat the pattern as plain text, not a regular expression
-h, --no-filenamedon’t put the file name in front of matches

Examples

  • grep error app.logLines containing "error"
  • grep -in "error" app.logAny case, with line numbers
  • grep -r TODO projectsSearch every file under projects
  • ls | grep .txtFilter another command’s output

Learn it step by step

learner@sandbox: ~bash (practice)
Note: Try grep here: your home directory has sample files. Press Try beside an example, or type your own.

A practice shell in your browser that behaves like bash on Linux for these commands. Nothing you type leaves the page.