Regular expressions (regex) are powerful tools used for pattern matching and text manipulation in various programming and scripting languages. They allow users to search, match, and manipulate text based on specific patterns.

Commonly Used Regular Expressions in Linux

Basic Concepts

  1. Literal Characters: Matches the exact characters.

  2. Metacharacters: Special characters that have specific meanings in regex.


Examples and Usage

  1. Literal Match

    Matches the exact characters in the text.

    grep "abc" file.txt
    

    This command searches for the string "abc".

  2. Dot (.)

    Matches any single character except a newline.

    grep "a.c" file.txt
    

    This command matches "abc", "a1c", "a-c", etc.

  3. Asterisk (*)

    Matches zero or more occurrences of the preceding element.

    grep "ab*c" file.txt
    

    This command matches "ac", "abc", "abbc", "abbbc", etc.

  4. Plus (+)

    Matches one or more occurrences of the preceding element.

    grep "ab+c" file.txt
    

    This command matches "abc", "abbc", "abbbc", etc., but not "ac".

  5. Question Mark (?)

    Matches zero or one occurrence of the preceding element.

    grep "ab?c" file.txt
    

    This command matches "ac" and "abc".

  6. Caret (^)

    Matches the start of a line.

    grep "^abc" file.txt
    

    This command matches any line that starts with "abc" .

  7. Dollar ($)

    Matches the end of a line.

    grep "abc$" file.txt
    

    This command matches any line that ends with "abc".

  8. Brackets ([])

    Matches any single character within the brackets.

    grep "[aeiou]" file.txt
    

    This command matches any line containing a vowel (a, e, i, o, u).

  9. Negation within Brackets ([^])

    Matches any single character not within the brackets.

    grep "[^aeiou]" file.txt
    

    This command matches any line containing a character that is not a vowel.

  10. OR (|)

    Matches either the pattern before or the pattern after the |.

    grep "abc\\|def" file.txt
    

    This command matches lines containing either "abc" or "def".

  11. Grouping ()

    Groups multiple tokens together and remembers the matched text.

    grep "\\(abc\\)\\{2,\\}" file.txt
    

    This command matches lines containing "abcabc" .

  12. Escaping ()

    Escapes a metacharacter to be used as a literal.

    grep "a\\.c" file.txt
    

    This command matches "a.c" in file.txt.


Advanced Examples

  1. Matching Word Boundaries

    Use \\b to match word boundaries.

    grep "\\bword\\b" file.txt
    

    This command matches the word "word" as a whole word.