LESSON · 1 OF 6

grep for finding text in a file

grep for finding text in a file

grep searches for a pattern inside a file and prints every line that matches.

bash
grep pattern file
grep root /etc/passwd

That prints every line of /etc/passwd containing the word "root". Usually more than one line comes back, because "root" appears in system paths too.

The flags you'll use daily

  • -i - case insensitive. Matches "Error", "ERROR", "error" the same.
  • -n - show the line number for each match.
  • -c - just count matches, don't print them.
  • -v - invert. Print lines that do NOT match.
bash
grep -in error /var/log/syslog       # case insensitive, with line numbers
grep -c nologin /etc/passwd          # how many accounts can't log in
grep -v '^#' /etc/hosts              # skip comment lines

That last one is a habit worth stealing:

bash
grep -v '^#' /etc/hosts

strips comments from any config file, leaving you with just the settings that actually apply.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute