Grep
Grep¶
grep is a powerful command-line utility in Linux used for searching plain-text data sets for lines that match a regular expression, and its name stands for "global regular expression print."
Basic Syntax¶
grep [OPTIONS] PATTERN [FILE...]
PATTERN: The regular expression or string to search for.FILE: The file or files to search within. If no file is specified,grepsearches the standard input.
Commonly Used Options¶
-i: Ignore case distinctions in both the PATTERN and the input files.-v: Invert the sense of matching, to select non-matching lines.-ror-R: Read all files under each directory, recursively.-n: Prefix each line of output with the line number within its input file.-l: Print only the names of files with at least one matching line.-c: Print only a count of matching lines per input file.-H: Print the file name for each match.
Examples¶
-
Basic Search
sh grep "hello" file.txtSearches for the string "hello" infile.txt. -
Case-Insensitive Search
sh grep -i "hello" file.txtSearches for "hello" in a case-insensitive manner infile.txt. -
Search Recursively
sh grep -r "hello" /path/to/directorySearches for "hello" in all files under/path/to/directory. -
Count Matching Lines
sh grep -c "hello" file.txtCounts the number of lines that contain "hello" infile.txt. -
Display Line Numbers
sh grep -n "hello" file.txtDisplays matching lines along with their line numbers infile.txt. -
Search for Whole Words
sh grep -w "hello" file.txtSearches for lines containing the whole word "hello" infile.txt. -
Invert Match
sh grep -v "hello" file.txtDisplays lines that do not contain "hello" infile.txt. -
Multiple Files
sh grep "hello" file1.txt file2.txtSearches for "hello" in bothfile1.txtandfile2.txt.
Using Regular Expressions¶
grep supports extended regular expressions (ERE) with the -E option, which allows for more complex pattern matching.
grep -E "hello|world" file.txt
This searches for lines containing either "hello" or "world" in file.txt.
Piping and Redirection¶
grep is often used in combination with other commands using pipes.
cat file.txt | grep "hello"
This searches for "hello" in the output of cat file.txt.
Grep in Scripts¶
grep is frequently used in shell scripts for processing and filtering text data. Here’s a simple example:
#!/bin/bash
# Script to find and count occurrences of "error" in log files
for file in /var/log/*.log; do
echo "Processing $file"
grep -c "error" "$file"
done