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