shell脚本实现IP地址转换成整型数值

createip.sh

#!/bin/bash 
i=0
while [ $i -lt 20 ]
do
	echo "192.168.0.$i">>ip.txt
	i=`expr $i + 1`
done

生成ip.txt文件

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14
192.168.0.15
192.168.0.16
192.168.0.17
192.168.0.18
192.168.0.19

转换脚本1,使用一个函数实现

#!/bin/bash 

convert_ip()
{
    
    
	local a=`echo $1 | cut -d '.' -f1`
	local b=`echo $1 | cut -d '.' -f2`
	local c=`echo $1 | cut -d '.' -f3`
	local d=`echo $1 | cut -d '.' -f4`

	local int=`expr $a \* 256 \* 256 \* 256 \
		+ $b \* 256 \* 256 \
		+ $c \* 256 \
		+ $d`
	echo $int
}

convert_ip $1

在这里插入图片描述

转换脚本2,读文件生成

#!/bin/bash 

OUTPUTFILE=int.txt
COUNT=1
if [ $# -eq 1 ] && [ -e $1 ]
then
	FILENAME=$1
else
	echo "file is not exists !"
	echo "input your ip manually:"
	FILENAME=""
fi
if [ -e $OUTPUTFILE ]
then 
	rm $OUTPUTFILE
fi

cat $FILENAME | while read IP
do
	a=`echo $IP | cut -d '.' -f1`
	b=`echo $IP | cut -d '.' -f2`
	c=`echo $IP | cut -d '.' -f3`
	d=`echo $IP | cut -d '.' -f4`

	int=`expr $a \* 256 \* 256 \* 256 \
		+ $b \* 256 \* 256 \
		+ $c \* 256 \
		+ $d`
	echo "[$COUNT]-------------------->">>$OUTPUTFILE
	echo "ip:		$IP" >> $OUTPUTFILE
	echo "int:	$int" >> $OUTPUTFILE
	echo "">>$OUTPUTFILE
	COUNT=`expr $COUNT + 1`
done
echo "DONE !!"
echo "the output file is :$PWD/$OUTPUTFILE"

结果

[1]-------------------->
ip:		192.168.0.0
int:	3232235520

[2]-------------------->
ip:		192.168.0.1
int:	3232235521

[3]-------------------->
ip:		192.168.0.2
int:	3232235522

[4]-------------------->
ip:		192.168.0.3
int:	3232235523

[5]-------------------->
ip:		192.168.0.4
int:	3232235524

[6]-------------------->
ip:		192.168.0.5
int:	3232235525

[7]-------------------->
ip:		192.168.0.6
int:	3232235526

[8]-------------------->
ip:		192.168.0.7
int:	3232235527

[9]-------------------->
ip:		192.168.0.8
int:	3232235528

[10]-------------------->
ip:		192.168.0.9
int:	3232235529

[11]-------------------->
ip:		192.168.0.10
int:	3232235530

[12]-------------------->
ip:		192.168.0.11
int:	3232235531

[13]-------------------->
ip:		192.168.0.12
int:	3232235532

[14]-------------------->
ip:		192.168.0.13
int:	3232235533

[15]-------------------->
ip:		192.168.0.14
int:	3232235534

[16]-------------------->
ip:		192.168.0.15
int:	3232235535

[17]-------------------->
ip:		192.168.0.16
int:	3232235536

[18]-------------------->
ip:		192.168.0.17
int:	3232235537

[19]-------------------->
ip:		192.168.0.18
int:	3232235538

[20]-------------------->
ip:		192.168.0.19
int:	3232235539


猜你喜欢

转载自blog.csdn.net/zxy131072/article/details/108531224