Grep

Search for text inside of files

Description

Grep is a really useful tool for quickly finding what you're looking for. If you know a file somewhere has some content, or just want to find all files with a certain pattern in them, Grep is the perfect tool for the job. It's written in C and highly optimized, meaning you can quickly search through lots of files.

$ grep [OPTIONS...] PATTERNS [FILES...]
  • OPTIONS can be any flags to change the way the search works, or matches are displayed

  • PATTERNS are a string containing one or more patterns to search for, separated by newline characters (\n). To put a newline character in an argument you can use the $'first\nsecond' syntax

  • FILES are the files to search through for the PATTERNS. If not specified, it will read from standard input (piping into grep). If in recursive mode with -r, it will default to the current directory but can be any directory

Simple example
$ grep something file.txt
And here is something.

See all documentation about the options with man grep

Options

The are a few common and really useful options to know in Grep:

  • -r: Recursively search a directory (default: current)

  • -v: Invert search, matching lines where no match

  • -i: Search case-insensitive (uppercase/lowercase doesn't matter)

  • -n: Print the line number of the match in the file

  • -o: Only output match (no text around)

  • -a: Show all matches (also binary files)

  • -b: Show byte-offset of matches

  • -l: List files that match instead of showing the match

  • Simple Regular Expressions (RegEx) are enabled by default in PATTERNS

    • -F: Treat PATTERNS as fixed strings, not regular expressions

    • -P: Use perl-compatible regular expressions (PCRE) including all advanced RegEx features

Some options are also available by using egrep (-E), fgrep (-F) and rgrep (-r) to quickly set the options without having to add the flag.

Tip: Also check out ripgrep for a Rust implementation of most grep features, with better defaults for recursive searching while skipping unnecessary files

Last updated