-1

I have a string with IP address:

172.27.16.123

I have a similar second string.

I need the four parts in four distinct variables i.e. v1=172, v2=27,v3=16,v4=123 The reason I want to this is that I want to take a third ip and see if it lies inbetween these two ips

I tried

echo $givenip | cut -d\. -f3  
harshit
  • 3,788
  • 3
  • 31
  • 54

3 Answers3

0

v11=$(echo $ip1 | cut -d. -f3)

echo $v11

harshit
  • 3,788
  • 3
  • 31
  • 54
0
export v1=`echo $givenip | cut -d\. -f3`
Ian Kenney
  • 6,376
  • 1
  • 25
  • 44
  • How could I use this if my delimiter character is a space? If i try: echo $var | cut -d\ -f3, or echo $var | cut -d\' ' -f3 is doesn't work. First one it says delimiter must be only one char, and the second one changes my Prompt to ">". – Btc Sources Jan 07 '15 at 20:45
  • `export v1=`echo $givenip | cut -d" " -f3` – Ian Kenney Jan 07 '15 at 20:52
0

Assuming your shell is bash, you should probably use arrays:

givenip=172.27.18.191
ip1=( $(sed 's/\./ /g' <<< 172.27.16.123) )
ip2=( $(sed 's/\./ /g' <<< 172.27.19.254) )
ip3=( $(sed 's/\./ /g' <<< $givenip) )

Then you can compare components:

givenip=172.27.18.191
ip1=( $(sed 's/\./ /g' <<< 172.27.16.123) )
ip2=( $(sed 's/\./ /g' <<< 172.27.19.254) )
ip3=( $(sed 's/\./ /g' <<< $givenip) )

if [ "${ip3[0]}" -ge "${ip1[0]}" -a "${ip3[0]}" -le "${ip2[0]}" ] &&
   [ "${ip3[1]}" -ge "${ip1[1]}" -a "${ip3[1]}" -le "${ip2[1]}" ] &&
   [ "${ip3[2]}" -ge "${ip1[2]}" -a "${ip3[2]}" -le "${ip2[2]}" ] &&
   [ "${ip3[3]}" -ge "${ip1[3]}" -a "${ip3[3]}" -le "${ip2[3]}" ]
 then echo $givenip is between two established IP addresses
 else echo $givenip is not between the two established IP addresses
 fi
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278