Grep Command
The grep (Global Regular Expression Print) command is one of the most useful tools in the Linux ecosystem. It allows you to search through the contents of files for specific patterns of text.
1. Basic Grep
The simplest way to use grep is to provide a search pattern and a file name.
Bash
grep "hello" messages.txt
2. Common Options
You can use these flags to make grep more powerful:
- -i: Ignore case (e.g., search for "HELLO" will match "hello").
- -r: Recursive search through all files in a directory.
- -n: Show the line number where the match was found.
- -v: Invert the search (show everything except the lines that match).
Bash
# Search for "error" in all files in the current folder, ignoring case grep -ri "error" .
3. Using Regular Expressions
Grep is at its best when you use Regular Expressions (RegEx) to find patterns.
- ^ (Caret): Matches the start of a line.
- $ (Dollar): Matches the end of a line.
Bash
# Find lines that START with "The" grep "^The" file.txt # Find lines that END with a period "." grep "\.$" file.txt