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