Linux commands
Browse topics

Searching text with grep

Version
unversioned
Review
Draft

Summary#

grep prints the lines that match a pattern. The pattern is a basic regular expression unless you pass -E for extended syntax or -F for literal text.

Syntax#

sh
grep -rn -- 'pattern' directory
grep -F -- 'literal text' file
grep -q -- 'pattern' file

Example#

sh
(
  set -eu
  export LC_ALL=C
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  mkdir src
  printf 'version = 1.2\nbuild = 102\n# TODO: add retries\n' > src/app.conf
  printf 'TODO: write docs\n' > src/notes.txt

  grep -rn 'TODO' src | sort
  echo '-- lines matching 1.2 as a regular expression'
  grep -c '1.2' src/app.conf
  echo '-- lines containing the literal text 1.2'
  grep -c -F '1.2' src/app.conf
  status=0
  grep -q 'FIXME' src/app.conf || status=$?
  echo "no match: exit status $status"
)

Expected output#

Text
src/app.conf:3:# TODO: add retries
src/notes.txt:1:TODO: write docs
-- lines matching 1.2 as a regular expression
2
-- lines containing the literal text 1.2
1
no match: exit status 1

Common mistakes#

grep exits with status 1 when nothing matches, which stops a script running under set -e. Use it in an if condition, or capture the status when you must tell no match (1) from an error (2). Avoid -q if you must detect all input errors, since finding a match can make it return 0 despite an error. An unescaped . matches any character in a line, and -c counts matching lines, not individual occurrences.

Version applicability#

This entry describes GNU grep. Other implementations, including BSD grep on macOS and BusyBox grep, support a different set of extensions.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0