Matching IP addresses using regular expressions in Shell scripts

Source: Internet
Author: User

Matching IP addresses using regular expressions in Shell scripts

This article describes how to use regular expressions to match IP addresses in Shell scripts. This article provides the implementation code directly. For more information, see

In O & M scenarios, we often need to use regular expressions on servers to match IP addresses.

Like other programming languages, shell can also use regular expression grouping for capturing. However, you can use arrays $ {BASH_REMATCH} instead of $1 or 1 to capture groups, for example, $ {BASH_REMATCH [1]}, $ {BASH_REMATCH [N]}

The following uses ip = "121.0.2.2" as an example. The shell script code is as follows (of course, You can implement it by using reverse CT to make a more general interactive script ):

The Code is as follows:

#! /Bin/bash

Ip = "121.0.2.2"

If [[$ ip = ~ ^ ([0-9] {1, 2} | 1 [0-9] [0-9] | 2 [0-4] [0-9] | 25 [0-5 ]). ([0-9] {1, 2} | 1 [0-9] [0-9] | 2 [0-4] [0-9] | 25 [0-5] ). ([0-9] {1, 2} | 1 [0-9] [0-9] | 2 [0-4] [0-9] | 25 [0-5] ). ([0-9] {1, 2} | 1 [0-9] [0-9] | 2 [0-4] [0-9] | 25 [0-5]) $]

Then

Echo "Match"

Echo $ {BASH_REMATCH [1]}

Echo $ {BASH_REMATCH [2]}

Echo $ {BASH_REMATCH [3]}

Echo $ {BASH_REMATCH [4]}

Else

Echo "Not match"

Fi

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.