grep is a command-line utility in Unix and Unix-like operating systems used for searching within files for lines that contain a match to a specified pattern and then printing those lines to the standard output. The name grep stands for “global regular expression print,” reflecting its heritage in the ed command g/re/p, where it would globally search for a regular expression and print the lines.
The utility is widely used for a variety of purposes, such as searching through logs, files, or streams of input to find specific patterns, checking for the presence of a string within files, and even complex pattern matching with its support for regular expressions. grep has become essential in the toolset of both developers and system administrators for its powerful searching capabilities.
The simplest form of a grep command is:
This command searches for the pattern in the file named filename. If the pattern is found, grep prints the line to the standard output.
-i: Ignore case (both uppercase and lowercase letters are considered the same).
-v: Invert match (select non-matching lines).
-r or -R: Recursively search directories for the pattern.
-l: List the names of files with matching lines, once, without duplicates.
-n: Prefix each line of output with the line number within its input file.
-E: Interpret the pattern as an extended regular expression (ERE).
Search for the word “error” in a file named log.txt:
Search recursively in all files under the current directory for the string “OpenAI”, ignoring case:
List all filenames in the current directory and its subdirectories where the string “2024” is found:
grep is highly versatile and features many more options and capabilities, including complex pattern matching, which makes it a powerful tool for text processing and data analysis tasks.