Linux command: grep
Find the lines you need
A school timetable may have many lines, but you may only need to find the entries containing the word biology. If the timetable is saved as timetable.txt, grep biology timetable.txt prints lines containing that word. grep does the same kind of search in other text files: it looks for text that matches a pattern and prints each matching line. A pattern can be a word, number, or phrase. This command finds access-log lines containing the characters 500:
grep ' 500 ' /var/log/nginx/access.log
The match only shows that those characters occur on the line. They might appear in a field other than the response code, so check the log format before counting matches as errors. Put quotes around a pattern containing spaces or shell wildcard characters so the shell passes it to grep unchanged.
Search for literal text or a pattern
Use -F when the search text should match literally instead of using regular-expression rules. In this example, -n adds line numbers and -- tells grep that following words are not options:
grep -F -n -- 'some_string' ./config.txt
To search files below sample-dir, use -r:
grep -r -n -F -- 'some_string' ./sample-dir
GNU grep -r skips symbolic links it finds during the recursive search, while -R follows them. Recursive search checks file contents; it does not make a structured format such as JSON into plain text.
GNU grep uses basic regular expressions by default. A regular expression is a small language for describing text patterns. Characters such as . and * have special meanings. -E selects extended regular expressions, where +, ?, and | act as additional operators. -F selects fixed-string matching. A pattern written for another tool may use a different set of rules.
Use matches in a command or script
GNU grep returns status 0 when it selects a line, 1 when it finds none, and 2 for an error. A no-match result is often normal. -c, as in grep -c, counts matching lines rather than every occurrence of a pattern. A shell pipeline's final status may hide an earlier failure, so check each command when the result matters.
-i ignores case, -v selects lines that do not match, and -l prints names of files with a match. This expression selects log lines beginning with warn: or error: and adds line numbers:
grep -nE '^(warn|error):' app.log
Use -q when a script only needs a yes-or-no answer; it suppresses matching lines. In normal GNU grep use, status 1 means no match and 2 means error. With -q, selecting a line yields status 0 even if another error also occurred. For large trees, narrow the starting folder and avoid printing sensitive results. When fields are quoted, escaped, or separated by a defined format, use a parser that understands it instead of treating a line match as a count of events.







