user2124648
user2124648

Reputation: 11

Bash new variable with other variable

I get the ip address like that :

Ip=`ifconfig | grep inet | grep -v -E 'inet6|127.0.0.1' | \
    tr -d [:alpha:] | tr -s [:space:] | cut -d: -f2`

I have an ip like this for instance : 10.1.0.76

I want to make a new variable with the Ip variable to have another ip, for instance my new variable will return : 10.1.0.178

Just the last number change, so I want to get just a part of Ip variable (10.1.0.) and add another number to the end.

I tried with sed but I always have mistakes like "there's no file call'd ..."

Can you help me ?

Upvotes: 0

Views: 164

Answers (3)

that other guy
that other guy

Reputation: 123680

You can use parameter expansion: It's simply: ${Ip%.*}.178

${Ip%.*} is the ip with the last dot and everything after it removed. The .178 is what you want to append after that.

Here it is in context:

# Your original expression
Ip=`ifconfig | grep inet | grep -v -E 'inet6|127.0.0.1' | \
    tr -d [:alpha:] | tr -s [:space:] | cut -d: -f2`

# assign a new variable with the ip with different end octet
newIp=${Ip%.*}.178

# Show new ip
echo "$newIp"

Upvotes: 2

Kent
Kent

Reputation: 195249

see this, I hope it is what you want:

kent$  echo $ip
10.1.0.76

kent$  echo $part
178

kent$  sed -r "s/(.*\.).*/\1$part/" <<< $ip
10.1.0.178

to set $ip with new value:

kent$  ip=$(sed -r "s/(.*\.).*/\1$part/" <<< $ip)

kent$  echo $ip
10.1.0.178

Upvotes: 0

kamituel
kamituel

Reputation: 35970

Well, given that you have IP in a format x.y.z.w, you can use perl regex:

$ echo "120.20.31.78" | perl -pe 's/(.*)\..*/$1\.123/'
120.20.31.123

This will repace last number ("78") with "123".

So, in your case (assuming your "Ip" variable is set correctly), it would be:

Ip=ifconfig | grep inet | grep -v -E 'inet6|127.0.0.1' | tr -d [:alpha:] | tr -s [:space:] | cut -d: -f2 | perl -pe 's/(.*)\..*/$1\.123/'

Upvotes: 1

Related Questions