Grep and fgrep are powerful command-line tools used to search for patterns or regex in text files or standard input. Here’s a comprehensive guide on how to use them:
Basic Usage
– grep pattern file: Searches for the pattern in the file.
– fgrep pattern file: Similar to grep,but uses fixed strings instead of regex.
Pattern Matching
– grep ‘hello world’ file: Searches for the exact phrase “hello world”.
– grep ‘hello\|world’ file: Searches for either “hello” or “world” using the \| operator.
– grep ‘^hello’ file: Searches for lines starting with “hello” using the ^ anchor.
– grep ‘world$’ file: Searches for lines ending with “world” using the $ anchor.
Regex Patterns
– grep ‘[a-zA-Z]’ file: Searches for any letter (lowercase or uppercase).
– grep ‘[0-9]’ file: Searches for any digit.
– grep ‘\bhello\b’ file: Searches for the whole word “hello” using word boundaries \b.
Options
– -i or –ignore-case: Makes the search case-insensitive.
– -v or –invert-match: Prints lines that do not match the pattern.
– -c or –count: Prints the number of matches instead of the matching lines.
– -n or –line-number: Prints the line numbers along with the matching lines.
Examples
– grep -i ‘hello’ file: Searches for “hello” in a case-insensitive manner.
– fgrep -v ‘hello’ file: Prints lines that do not contain “hello”.
– grep -c ‘hello’ file: Prints the number of lines containing “hello”.
Pipe Output
You can pipe the output of other commands to grep or fgrep to filter the results:
– ls -l | grep ‘hello’: Searches for “hello” in the output of the ls -l command.
Remember to use quotes around your pattern to prevent the shell from interpreting special characters.