LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Last digit minus ONE... (https://www.linuxquestions.org/questions/programming-9/last-digit-minus-one-873347/)

NetRock 04-06-2011 09:27 AM

Last digit minus ONE...
 
Hi All,

I am about configuring IP addresses for different workstations. in this process, after running few bash scripts to get the right subnet mask, i need to remove one digit from the last IP value, what i mean is:
ex, if i get ip=192.168.0.254 i need 192.168.0.253 so whatever Ip address i get i need to minus only one digit from the last IP addresswhatever it is. What is the best way to do this....

Code:

$ip | cut -d"." -f4......
or $ip | awk -F"." ;'{print $4}'...


Thank you for your help.

paulsm4 04-06-2011 09:58 AM

I'd say "Curtain B". You might be able to do something like this (I haven't tested):
Code:

$ip | awk -F"." ;'{printf "%d.%d.%d.%d", $1, $2, $3, $4 - 1}'

Guttorm 04-06-2011 10:04 AM

Hi.

I agree, awk is better since it can do simple math.

Code:

echo $ip | awk -F"." '{printf "%d.%d.%d.%d", $1, $2, $3, $4 - 1}'
But what if the last digit is 0?

NetRock 04-06-2011 11:28 AM

Thanks for the reply. it works as expected but yup how about the last 0 digit, i guess must test the IP address before running the code so if has 0 at the end ignores the IP address ...

grail 04-06-2011 11:38 AM

Well it depends on whether you want go all bash or use outside commands:
Code:

ip='192.168.0.254'

#help from awk
echo $ip | awk -F. '$4=$4-1' OFS="."

# all bash
last=${ip##*.}
(( last-- ))

echo ${ip%.*}.$last

Of course none of this covers the zero case, but you may also wish to ask do you really want to ignore it or maybe set it to 255 and take one from the next octet.
Of course this would require a lot more testing and work.

NetRock 04-06-2011 12:39 PM

Thanks Garil,

Once Again Short and Sweet...!!


All times are GMT -5. The time now is 04:52 PM.