ipfile.txt
格式如下:
ServerA 127.0.0.1
ServerB 192.168.1.254
ServerC 4.2.2.1
shell脚本的期望输出:
ServerA Class A
ServerB Class C
ServerC Class A
我想不出更好的方法来只提取第一个八位字节。到目前为止,我的脚本是:
#!/bin/bash
# Take input IP from file and classify according to classful addressing.
while read ip;do
octet=$(awk -F'[ .]' '{print $2}' ipfile.txt)
if [[ "$octet" -ge 1 && "$octet" -le 127 ]];then
echo "ServerA Class A"
fi
if [[ "$octet" -ge 128 && "$octet" -le 191 ]];then
echo "ServerB Class B"
fi
if [[ "$octet" -ge 192 && "$octet" -le 223 ]];then
echo "ServerC Class C"
fi
done < ipfile.txt
我收到语法错误:
./ipclassgen.sh: line 7: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 10: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 13: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 7: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 10: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 13: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 7: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 10: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 13: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 7: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 10: [[: 127
192
4: syntax error in expression (error token is "192
4")
./ipclassgen.sh: line 13: [[: 127
192
4: syntax error in expression (error token is "192
4")
如何在不使用 awk 和指定文件的情况下做到这一点。我也不确定语法错误在哪里。
您将文件逐行读取到
ip
变量中,但从不使用它。然后将所有行的第二个字段分配给octet
变量,由<NL>
(\n, 0x0A) 分隔,再次读取文件。然后在进行测试时bash
偶然发现了多行。octet
改为尝试:另请注意,不硬编码服务器名称而是使用
server
从文件中读取的变量可能更聪明:PS:您甚至可以
read
为您拆分线路: