You can use `grep` to search for patterns within a file by following this syntax:
grep [OPTIONS] PATTERN FILENAME
Example:
To search for the word "apple" in a file called `fruits.txt`, use:
grep "apple" fruits.txt
This will print the lines in the file `fruits.txt` that contain the word "apple."
Common Options:
- `-i`: Ignore case (e.g., `grep -i "apple" fruits.txt` will match "Apple", "APPLE", etc.)
- `-r`: Search recursively in directories (e.g., `grep -r "apple" /path/to/directory/`)
- `-n`: Show line numbers where the pattern occurs (e.g., `grep -n "apple" fruits.txt`)
- `-v`: Invert match, showing lines that do **not** contain the pattern (e.g., `grep -v "apple" fruits.txt`)
- `-w`: Match whole words only (e.g., `grep -w "apple" fruits.txt`)
- `-l`: List only filenames containing the match (e.g., `grep -l "apple" *.txt`)
- `-A NUM`: Show `NUM` lines **after** the match (e.g., `grep -A 2 "apple" fruits.txt`)
- `-B NUM`: Show `NUM` lines **before** the match (e.g., `grep -B 2 "apple" fruits.txt`)
- `-C NUM`: Show `NUM` lines **before and after** the match (e.g., `grep -C 2 "apple" fruits.txt`)
Searching with Regular Expressions:
You can use regular expressions with `grep` for more powerful searches:
- `^`: Matches the beginning of a line (e.g., `grep "^apple" fruits.txt` will find lines starting with "apple")
- `$`: Matches the end of a line (e.g., `grep "apple$" fruits.txt` will find lines ending with "apple")