Search for something in a file
grep something file
Search for something in multiple files
grep something file file1 file2 file 3
Search for something everywhere in the current directory
grep something *
Search for something only if it occurs at the beginning of a line
grep ^something *
Search for something only if it occurs at the end of a line
grep something$ *
Search for whole word everywhere in the current directory
grep -w something *
Search for only word everywhere in the current directory
grep -o something *
Ignore case, when searching everywhere in the current directory
grep -i something *
Search for something including all subdirectories in the current directory
grep -r something *
Ignore something while searching everywhere in the current directory
grep -v something *
Show Lines That Match Search String
grep -x "something" *
Show Names of Matching Files
grep -l something *
Count the Number of Matches
This is handy to use to check if a setting exists or not. This way to use grep -c. This outputs (not return as exit code), the number of lines that match the pattern searched for (STIG items – checks), so 0 if there is not a match or 1 or more if there is a match.
grep -c something *
If you wanted to check that the pattern is matched 3 or more times, you would do:
grep --count --ignore-case "something" --max-count=3
echo Two too. | grep -i t[ow]o
Match numerical digits
echo 123 test 345 hello world 12 | grep [[:digit:]]
echo two twoo not too | grep -o two*
echo For love of $ | grep \\$
Display Number of Lines Before or After a Search String
Use -A and a number of lines to display after a match: grep -A 3 phoenix sample – this command prints three lines after the match.
Use -B and a number of lines to display before a match: grep -B 2 phoenix sample – this command prints two lines before the match.
Use -C and a number of lines to display before and after the match: grep -C 2 phoenix sample – this command prints two lines before and after the match.
Search for something in the current directory, showing two lines before and after the matches along with their line numbers.
grep -n -C 2 something file
Limiting Output to a Fixed Number of Lines. Limit the number of lines by adding the -m option and a number to the command.
This prints the first two matches it finds in the file.
grep -m2 something file
If you do not specify a file and search all files in a directory, the output prints the first two results from every file along with the filename that contains the matches.
Big thanks to phoenixnap.com!
Set environment variable to output strings in red
grep -n (show line numbers)
echo happy ever after in the marketplace | grep -n [aeiou]
Show line numbers of those lines having more than one occurrence of the regular expression.
echo happy ever after in the marketplace | grep -on marketplace | cut -d: -f1 | uniq -