To match an IP address with a regular expression in a shell script

Source: Internet
Author: User
Tags regular expression

This article mainly introduced the shell script to match the IP address through the regular expression, this article directly gives the realization code, needs the friend to be possible to refer to under

In the operational dimension scenario, we often need to match the IP address with a regular expression on the server.

The shell, like other programming languages, can also use regular packet captures, but you cannot use a form such as $1 to capture groupings, which can be obtained through array ${bash_rematch}, such as ${bash_rematch[1]},${bash_rematch[n] }

Take ip= "121.0.2.2" for example, the shell script code is as follows (of course, you want to make a more general interactive script that can be implemented by expect):

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

Related Article

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.