grep Linux Command
Searches for patterns (text or regex) inside files and prints matching lines.
What does grep do?
Searches for patterns (text or regex) inside files and prints matching lines.
Syntax
grep [options] pattern filePractical example
grep -r 'password' /etc/Questions about grep
How do I search for a pattern in a file?
Use `grep 'pattern' filename` to find all lines containing the pattern. The pattern can be plain text or a regular expression.
How do I do a case-insensitive search?
Use `grep -i 'pattern' filename` to ignore case when searching. This matches 'Pattern', 'PATTERN', 'pattern', etc.
How do I search recursively in directories?
Use `grep -r 'pattern' /path/` to search all files in a directory and its subdirectories. Add `-l` to show only filenames.
How do I count matching lines?
Use `grep -c 'pattern' filename` to count the number of lines that match the pattern. This is useful for statistics.
How do I show line numbers in grep?
Use `grep -n 'pattern' filename` to display the line number alongside each matching line.
How do I invert a grep match?
Use `grep -v 'pattern' filename` to show all lines that do NOT match the pattern. This is useful for filtering out unwanted lines.
How do I search for whole words only?
Use `grep -w 'word' filename` to match only whole words. This prevents matching 'password' when searching for 'pass'.
How do I search multiple files?
Use `grep 'pattern' file1 file2 file3` or `grep 'pattern' *.txt` with a glob pattern to search multiple files at once.
Related Search Commands
findSearches for files and directories in a directory hierarchy by name, type, size, etc.
locateQuickly finds files by name using a pre-built database (run updatedb to refresh).
xargsBuilds and executes command lines from standard input (useful with pipes).
whichShows the full path of the executable that would run for a given command.
trTranslates, deletes, or squeezes characters from standard input.
whereisLocates the binary, source, and manual page files for a command.