linux grep regex

In Linux, grep supports regular expressions (regex), which allow for pattern matching more complex than simple substring searches. Here’s how you can use grep with regular expressions:

  1. Basic regex search:
    Search for lines containing a pattern defined by a regular expression:
   grep 'regular_expression' filename
  1. Case-insensitive search:
    Perform a case-insensitive regex search:
   grep -i 'regular_expression' filename
  1. Extended regex syntax:
    Use the -E option to enable extended regular expressions (this is the default on many systems):
   grep -E 'regular_expression' filename
  1. Search for lines starting with a pattern:
    Only match lines that begin with the specified pattern:
   grep '^regular_expression' filename
  1. Search for lines ending with a pattern:
    Only match lines that end with the specified pattern:
   grep 'regular_expression$' filename
  1. Use character classes:
    Search for lines that contain any vowel (both cases):
   grep '[aeiouAEIOU]' filename
  1. Multiple patterns:
    Search for lines that contain any of the given patterns:
   grep -E '(pattern1|pattern2|pattern3)' filename
  1. Quantifiers:
    Search for lines with exactly three digits:
   grep -E '(\\d){3}' filename
  1. Character ranges:
    Search for lines that contain a lowercase letter between ‘a’ and ‘m’:
   grep '[a-m]' filename
  1. Greedy and lazy quantifiers:
    Search for the longest string that starts with ‘foo’ and ends before a ‘bar’:
   grep -E 'foo.*bar' filename grep -E 'foo.*?bar' filename

  1. Grouping and backreferences:
    Search for lines that contain the same two-digit number twice:
   grep -E '(\\d\\d).*\\1' filename
  1. Negation:
    Search for lines that do not contain a digit:
   grep -v '[0-9]' filename
  1. Bracket expressions:
    Search for lines that contain any character except the specified ones:
   grep -E '[^aeiou]' filename
  1. Recursive search with regex:
    Search recursively for a pattern in all files within a directory:
   grep -r 'regular_expression' /path/to/directory
  1. Using Perl-compatible regular expressions (PCRE):
    Use the -P option for Perl-compatible regular expressions:
    bash grep -P 'regular_expression' filename

Remember to enclose your regular expressions in single quotes ' to prevent the shell from interpreting any special characters. Adjust the regular expressions according to your specific search requirements.

This entry was posted in File & Directory, Grep Command and tagged , , . Bookmark the permalink.