JIYIK CN >

Current Location:Home > Learning > OPERATING SYSTEM >

Pattern matching in Bash

Author:JIYIK Last Updated:2025/03/23 Views:

Pattern matching is a powerful feature in Bash that allows you to compare a string to a pattern to find a match or perform an action based on the result of the comparison. This is useful in situations such as checking the format of a string or extracting a substring from a larger string.

This article discusses how to do pattern matching in Bash and introduces some common operators and techniques used in pattern matching.


Pattern matching using the =~ operator

To understand how pattern matching works in Bash, let's first look at =~the operator used to perform pattern matching. This operator takes two operands: the string to match and the pattern to compare.

For example, suppose we have a string called my_string that contains a URL and we want to check whether it starts with "http" or "https". We can use the =~ operator to perform this comparison.

my_string="https://www.example.com"

if [[ $my_string =~ ^https?:// ]]; then
  echo "The string starts with a valid URL"
fi

Output:

The string starts with a valid URL

In the code above, we use =~the operator to ^https?://compare the my_string variable to the pattern . ^The character indicates that the pattern must match the beginning of the string, while ?the character indicates that the preceding character (in this case, the s in https) is optional.

This means that the pattern will match "http://" or "https://" at the beginning of the string.

If the comparison is successful, the if statement is executed and the message "The string starts with a valid URL" is printed.


Using *the operator for pattern matching

Another common operator in pattern matching is *the (asterisk) character, which indicates that the preceding character can be matched zero or more times. For example, suppose we have a string containing a number and we want to check whether it is a valid decimal number with up to two decimal places.

We can use *the operator to perform this comparison.

my_string="3.14"

if [[ $my_string =~ ^[0-9]+.[0-9]{0,2}$ ]]; then
echo "The string is a valid decimal number"
else
echo "The string is not a valid decimal number"
fi

Output:

The string is a valid decimal number

In the above code, we use =~the operator to ^[0-9]+\.[0-9]{0,2}$compare the my_string variable with the pattern . ^The character indicates that the pattern must match the beginning of the string, whereas $the character indicates that the pattern must match the end of the string.

[0-9]The character class matches any digit from 0 to 9, and the + character indicates that the preceding character class must match one or more times.

We use the \ (backslash) character to escape .the (dot) character, which is used to match any single character. {0,2}The quantifier means that the preceding character (in this case, [0-9]the character class) must be matched zero to two times.

This means that the pattern will only match numbers with up to two decimal places, such as "3.14" or "42.00".

If the comparison is successful, the if statement is executed and the message "This string is a valid decimal number" is printed.


Pattern matching using subpatterns

Another common technique used in pattern matching is the use of subpatterns. A subpattern is a portion of a pattern enclosed in parentheses that can be used to group characters or to refer to a matching substring within the input string.

For example, suppose we have a string containing a date in the format "YYYY-MM-DD" and we want to extract the year, month, and day from the string. We can use a subpattern to perform this extraction.

my_string="2022-11-20"

if [[ $my_string =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
  year=${BASH_REMATCH[1]}
  month=${BASH_REMATCH[2]}
  day=${BASH_REMATCH[3]}

  echo "The year is: $year"
  echo "The month is: $month"
  echo "The day is: $day"
fi

Output:

The year is: 2022
The month is: 11
The day is: 20

In the above code, we use =~the operator to match the my_string variable with ^([0-9]{4})-([0-9]{2})-([0-9]{2} )$the pattern. The ^and $characters indicate that the pattern must match the entire string, while the ([0-9]{4})、([0-9]{2})and ([0-9]{2})subpatterns match the year, month, and day portions of a date respectively.

If the comparison succeeds, the if statement is executed to extract the year, month, and day from the input string. The extracted substrings are stored in the BASH_REMATCH array and can be accessed using indexes 1, 2, and 3, which correspond to the first, second, and third subpatterns, respectively.

In summary, pattern matching is a powerful feature in Bash that allows you to compare a string to a pattern to find a match or perform an action based on the comparison result. This can be =~done using the operator, which takes a string and a pattern as operands and returns true if the string matches the pattern.

Common operators and techniques used in pattern matching include *the (asterisk) operator, which matches the preceding character zero or more times, and subpatterns, which allow you to group characters or extract matching substrings from the input string.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to decompress x.tar.xz format files under Linux

Publish Date:2025/04/08 Views:186 Category:OPERATING SYSTEM

A lot of software found today is in the tar.xz format, which is a lossless data compression file format that uses the LZMA compression algorithm. Like gzip and bzip2, it supports multiple file compression, but the convention is not to compr

Summary of vim common commands

Publish Date:2025/04/08 Views:115 Category:OPERATING SYSTEM

In Linux, the best editor should be vim. However, the complex commands behind vim's powerful functions also make us daunted. Of course, these commands do not need to be memorized by rote. As long as you practice using vim more, you can reme

Detailed explanation of command return value $? in Linux

Publish Date:2025/04/08 Views:58 Category:OPERATING SYSTEM

? is a special variable. This variable represents the return value of the previous command. That is to say, when we run certain commands, these commands will return a code after running. Generally, if the command is successfully run, the re

Common judgment formulas for Linux script shell

Publish Date:2025/04/08 Views:159 Category:OPERATING SYSTEM

In shell script programming, predicates are often used. There are two ways to use predicates, one is to use test, and the other is to use []. Let's take a look at how to use these two methods through two simple examples. Example 1 # test –

How to use the Linux file remote copy command scp

Publish Date:2025/04/08 Views:151 Category:OPERATING SYSTEM

Scp copies files between two hosts over the network, and the data is encrypted during transmission. Its underlying layer uses ssh for data transmission. And it has the same authentication mechanism and the same security level as ssh. When u

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial