Skip to content

Latest commit

 

History

History
92 lines (53 loc) · 2.87 KB

01.Basic_regex_patterns.md

File metadata and controls

92 lines (53 loc) · 2.87 KB

Basic Regex Patterns in Linux Scripting

Regular expressions, or regex, are powerful tools for pattern matching and text manipulation in Linux scripting. This tutorial will guide you through the usage of basic regex patterns, providing essential knowledge for effective text processing.

Introduction to Regex

A regular expression is a sequence of characters that defines a search pattern. It's a versatile tool used for matching, searching, and manipulating text. In Linux, regular expressions are commonly used with commands like grep, sed, and awk.

Literal Characters

Literal characters in a regex pattern match themselves. For example:

grep "apple" fruits.txt

This command searches for the exact string "apple" in the file fruits.txt.

Wildcard .

The dot (.) in a regex pattern represents any single character. For example:

grep "a.e" words.txt

This command matches strings like "ale," "axe," and "ate" in the file words.txt.

Character Classes []

Character classes allow you to specify a set of characters. For example:

grep "[aeiou]" vowels.txt

This command matches any line in vowels.txt that contains at least one vowel (a, e, i, o, or u).

Negation in Character Classes [^]

Negation in character classes matches any character that is not in the specified set. For example:

grep "[^0-9]" text.txt

This command matches lines in text.txt that do not contain any numeric digit.

Quantifiers *, +, ?

Quantifiers specify the number of occurrences of the preceding character or group. For example:

  • * matches 0 or more occurrences.
  • + matches 1 or more occurrences.
  • ? matches 0 or 1 occurrence.
grep "o*" animals.txt

This command matches lines in animals.txt with zero or more "o" characters.

Anchors ^ and $

Anchors specify the start (^) or end ($) of a line. For example:

grep "^start" lines.txt

This command matches lines in lines.txt that start with the word "start."

Escape Special Characters \

To match special characters literally, you need to escape them with a backslash (\). For example:

grep "3\." numbers.txt

This command matches lines in numbers.txt containing the string "3."

Conclusion

Understanding basic regex patterns is essential for effective text processing in Linux scripting. Whether you are searching for specific strings, extracting data, or performing complex replacements, regex provides a powerful and flexible solution. Experiment with these basic patterns to build your regex skills and enhance your Linux scripting capabilities.