我有变量
network="198.168.1.x" # for ex. 198.168.1.254
我想创建新变量:
next_serv="198.168.1.(x-1)" # for ex. 198.168.1.253
max_host="198.168.1.(x-2)" # for ex. 198.168.1.252
怎么做?
答案1
network="198.168.1.254"
IFS="." read -r a b c d <<< "$network"
next_serv="$a.$b.$c.$(($d-1))"
echo "$next_serv"
输出:
198.168.1.253
答案2
简单的方法是将值拆分为“.”。标记并进行算术,将结果再次放在一起。
使用 awk(处理分隔符等):
this_serv=192.168.1.100
next_serv=$(echo $this_serv | awk -F. '{printf "%d.%d.%d.%d", $1,$2,$3,$4-1}')
答案3
使用参数扩展:
$ network="198.168.1.254"
$ next_serv="${network%.*}.$((${network##*.} - 1))"
$ max_host="${network%.*}.$((${network##*.} - 2))"
$ echo "$next_serv"
198.168.1.253
$ echo "$max_host"
198.168.1.252