TOOL » LINUX » PACKAGE

Grep

Syntax

shell
grep OPTIONS PATTERN FILE
OptionDescription
-r --recursiveRecursive (when FILE is a FOLDER)
-c --countPrint a count of matching lines.
-C --context -NUMPrint NUM lines of output context.
-v --invert-matchInvert the sense of matching, to select non-matching lines.
-o --only-matchingPrint only the matched (non-empty) parts of matching lines.
-l --files-with-matchesShow only the names of files that contain matches.
-f --fileObtain patterns, one per line, from the given file. Use - for stdin.
-E --extended-regexpInterpret PATTERN as extended regular expressions.
-F --fixed-stringsInterpret PATTERN as fixed strings.
-m --max-countStop reading a file after NUM matching lines.
-P --perl-regexpInterpret patterns as Perl-compatible regular expressions (PCREs).
-q --quiet --silentDo not write anything to STDOUT. Useful when only status code matters.
--excludeExclude FILEs

Examples

Recursive (with exclusions) grep.

shell
grep -r --exclude="*.swp" 'search_value' .

Search using extended regexp in a file.

shell
grep -Ev 'boo|foo' file

Obtain patterns from stdin.

shell
echo 'pattern' | grep -f - file

Find and replace all matches recursively in files:

shell
grep --files-with-matches foo | xargs -n 1 sed -i 's/foo/boo/g'