What grep does with its input
grep reads each named file, or standard input when no file is named, one line at a time. For every line it checks whether the pattern matches somewhere in the line. Matching lines are written to standard output, and by default nothing else is printed. The pattern is a regular expression in BRE by default, so the rules from the previous unit apply. With -E you get ERE, and with -F the pattern is a fixed string and no characters are special.
The input is a stream. grep does not need the whole file in memory, and it works equally well on a pipe from another command. That is why grep sits in the middle of so many pipelines.
Making a small test file
The examples below use a small log file that you create in your lab home directory. Creating the file first means every command has a known answer.
printf 'NFO start\nERROR disk full\nINFO retry\nerror timeout\nWARN slow\n'> app.logThis file has five lines, two of which contain an error in some form. The capital ERROR and the lowercase error are different strings to grep unless you ask it to ignore case.
The options you will use every day
The most useful options change what is printed. -i ignores case, -n prints line numbers, -c prints only the count of matching lines, and -v inverts the match so that non-matching lines are printed. -w requires the match to be a whole word, and -x requires it to be the whole line.
grep -in error app.log
grep -c INFO app.log
grep -v INFO app.logThe first command prints the two error lines with their numbers, because -i matches both spellings. The second prints 2, the number of INFO lines. The third prints the three lines that do not contain INFO. Notice that -c and -v change the output without changing the matching rule, which is why they combine well: grep -vc counts the non-matching lines.
Use -o to print only the matched part of each line. It is the fastest way to pull a value, such as an IP address or a version number, out of a longer line.
Context around a match
When a match matters only because of the lines around it, use -A for lines after, -B for lines before, and -C for both. grep prints a separator line between groups that are not adjacent. Context is especially useful with log files, where the cause of an error is usually a few lines above the message.
grep -B1 -A1 ERROR app.logThis prints the ERROR line with one line before and one line after it. Because the context lines are printed as they are, you can read the surrounding events without opening the whole file.
Searching many files
Give grep several file names to search them all, and each matching line is prefixed with its file name. With -r grep descends into directories. Use -l to list only the names of files that contain a match, and -L to list files that contain none. These options turn grep into a quick way to answer which files mention a symbol or setting.
mkdir -p notes
printf 'ODO fix\n'> notes/a.txt
printf 'one\n'> notes/b.txt
grep -rl TODO notesThe final command prints notes/a.txt only. The file notes/b.txt does not contain the word, so it is not listed.
Exit status: grep as a test
grep reports its result through the exit status. It returns 0 when at least one line matched, 1 when no line matched, and 2 when an error occurred, such as a file that does not exist. The quiet option -q suppresses output and only sets the status, which makes grep a natural condition in a script.
grep -q WARN app.log; echo "found=$?"
grep -q PANIC app.log; echo "found=$?"The first line prints found=0 and the second prints found=1. The status 2 is the one to watch for in scripts, because it means the search itself failed. Treating a 1 and a 2 the same way hides real problems, such as a mistyped file name.
Whole words, whole lines, and case
Plain substring matching is often too loose. The word log matches inside blog and logger, and the search for INFO should not fire on INFORMATION. The option -w asks for whole words, meaning the match must be bordered by non-word characters or the ends of the line. The option -x is stricter, because the entire line must match, which is the right tool for checking that a line equals a given value.
printf 'og\nblog\nlogger\nlog file\n'| grep -w logThis prints log and log file. The lines blog and logger are rejected because the match is inside a longer word. Case is controlled separately with -i, and it applies to letters only, so a pattern with digits or punctuation is unaffected by it.
When you combine several patterns, use -e once for each one. A line is printed when it matches any of them, which is an OR across patterns. This is simpler than writing an alternation when the patterns are unrelated words.
grep -e ERROR -e WARN app.logThe output contains the ERROR and WARN lines, and the INFO lines are skipped. Use -f with a file of patterns when the list grows beyond a handful of words.
Fixed strings and a common trap
Patterns often contain characters that have special meaning, such as dots in an IP address or brackets in a log line. With -F grep treats the whole pattern as literal text, which is both safer and faster for plain words. Without it, the dot in 10.0.0.1 matches any character.
The trap is quoting. Always put the pattern in single quotes, because an unquoted pattern containing a star or a bracket may be expanded by the shell as a file name before grep sees it. The unit on quoting explains why that happens.